在获取has_many:x,:through =>时遇到问题:y在控制台中工作 [英] Problems getting has_many :x, :through => :y to work in the console

查看:52
本文介绍了在获取has_many:x,:through =>时遇到问题:y在控制台中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建新的Rails应用(终端)

Create new Rails app (terminal)

rails new hmt
cd hmt


生成模型,支架,数据库模式等(终端)


Generate models, scaffolding, DB schema, etc (terminal)

rails g model magazine name
rails g model reader name
rails g model subscription magazine:references reader:references

根据生成的数据库架构(终端)创建表

Make tables based on generated DB schema (terminal)

rake db:migrate


检查是否已正确创建表(终端)


Check if tables are created ok (terminal)

rails c

(Rails控制台)

Magazine.column_names
Reader.column_names
Subscription.column_names


在模型/(magazine.rb)中指定关系


Specify relationships in models/ (magazine.rb)

class Magazine < ActiveRecord::Base
  has_many :subscriptions
  has_many :readers, :through => :subscriptions
end

(reader.rb)

(reader.rb)

class Reader < ActiveRecord::Base
  has_many :subscriptions
  has_many :magazines, :through => :subscriptions
end

(subscription.rb)

(subscription.rb)

class Subscription < ActiveRecord::Base
  belongs_to :reader
  belongs_to :magazine
end


添加一些数据(Rails控制台)


Add some data (Rails console)

vogue = Magazine.create!(:name => "Vogue")
bob = Reader.create!(:name => "Bob")
bob.subscriptions << vogue


最后一行产生错误


The last line there yields an error

ActiveRecord::AssociationTypeMismatch: Subscription(#70321133559320) expected, got Magazine(#70321133295480)

我在做什么错了?

推荐答案

在这里bob.subscription期望vogue成为Subscription模型的对象,因此会引发错误.因此,代替此方法,创建新的订阅为:-Subscription.create(magazine_id:vogue.id,reader_id:bob.id)

Here bob.subscription expects vogue to be an object of Subscription model hence it rises error. Hence instead of this create new Subscription as:- Subscription.create(magazine_id: vogue.id, reader_id: bob.id)

这篇关于在获取has_many:x,:through =&gt;时遇到问题:y在控制台中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆