Trouble with ActiveRecord associations and collection.build


#1

Hi Everyone,

I’ve encountered an interesting problem today; I’m setting up an
application with locations, where each location has_many :events. The
event model has a datetime field, called “service_at.”

I’m working with Timezones, so I’ve rewritten my accessor methods for
service_at to automatically convert the service_at from UTC to Local or
the reverse. The timezone data is stored on the location in this
example.

The problem I’m encountering is that I can’t reference the parent
during a build() operation.

So the following code:
location = Location.find(1)
event = location.events.build(params[:event])

Creates a situation where the custom service_at= method can’t access
the location data.

def service_at=(time)
logger.info(“converting #{time} to UTC”)
logger.info(self.to_yaml)
time = location.tz.local_to_utc(time) unless location.nil?
logger.info("#{time} to be saved.")
write_attribute(:service_at, time)
end

Pardon my debugging code, but the output in the console looks like this
(assuming that the service_at I’m passing is the datetime December 14,
2006, 10:00am)

converting Thu Dec 14 10:00:00 UTC 2006 to UTC
— !ruby/object:Event
attributes:
project_id: 1
location_id:
service_at:
workers_needed: 1
total_hours: 8
new_record: true

Thu Dec 14 10:00:00 UTC 2006 to be saved.

As you’ll notice, the event instance doesn’t have a record of the
location_id or Location object at all.

I can’t simply use a before_save callback, because creating an event
using Event.new and passing in location_id as a parameter will cause
the above code to function the way I expect.

So, any suggestions on why the events.build() method isn’t making the
location object available to it’s newly created association?

-Jared