问题
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