Problems getting has_many :x, :through => :y to work in the console

感情迁移 提交于 2020-01-05 12:16:12

问题


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 console)

Magazine.column_names
Reader.column_names
Subscription.column_names

Specify relationships in models/ (magazine.rb)

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

(reader.rb)

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

(subscription.rb)

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

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)

What am I doing wrong?


回答1:


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)



来源:https://stackoverflow.com/questions/20461916/problems-getting-has-many-x-through-y-to-work-in-the-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!