Passing association parameters on ActiveRecord object creation
In my application I have 2 classes like this:
class City < ActiveRecord::Base
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :city
attr_accessible :title, :city_id
end
If I create city object:
city = City.create!(:name => 'My city')
and then pass parameters to create event li开发者_JAVA百科ke this:
event = Event.create!(:name => 'Some event', :city => city)
I get
event.city_id => null
So the question is - is it possible to pass parameters in such a way to get my objects connected, what am I doing wrong? Or should I use other ways (like
event.city = city
) ?
Generally this happens when you have an attr_accessor
that excludes or an attr_protected
that includes the :city
attribute on Event
. Allowing :city_id
to be accessible does not automatically allow :city
to be so.
(NB: this answer provided as per the discussion in comments above, and thus community-wiki.)
This will work:
city = City.create!(:name => "London")
event = Event.create!(:name => "Big Event")
event.city = city
event.save
Alternatively, if Event.validates_presence_of :city
, and thus the Event.create!
call will fail without a City
, you could do this:
event = Event.new(:name => 'Big Event').tap do |e|
e.city = city
e.save!
end
You should be doing
event = Event.create!(:name => 'Some event', :city_id => city.id)
精彩评论