lightalloy
lightalloy

Reputation: 1165

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 like 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

) ?

Upvotes: 3

Views: 3173

Answers (3)

James A. Rosen
James A. Rosen

Reputation: 65232

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

Upvotes: 4

thomasfedb
thomasfedb

Reputation: 5983

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

Upvotes: 1

alex.zherdev
alex.zherdev

Reputation: 24164

You should be doing

event = Event.create!(:name => 'Some event', :city_id => city.id)

Upvotes: 0

Related Questions