Passing association parameters when creating an ActiveRecord object

In my application, I have 2 classes:

class City < ActiveRecord::Base
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :city
  attr_accessible :title, :city_id
end

If I create a city object:

city = City.create!(:name => 'My city')

and then pass parameters to create such an event:

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 as to link my objects, what am I doing wrong? Or should I use other ways (e.g.

event.city = city

)

+3
source share
3 answers

This usually happens when you have attr_accessorone that excludes or attr_protectedthat includes the attribute :cityon Event. Allow access to :city_iddoes not allow automatically :city.

(NB: , , community-wiki.)

+4

:

city = City.create!(:name => "London")

event = Event.create!(:name => "Big Event")
event.city = city
event.save

, Event.validates_presence_of :city, , , Event.create! City, :

event = Event.new(:name => 'Big Event').tap do |e|
  e.city = city
  e.save!
end
+1

You have to do

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

Source: https://habr.com/ru/post/1750991/


All Articles