Forum: Ruby on Rails Trouble with ActiveRecord associations and

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Bc830f45d04281f54aabc2734303f895?d=identicon&s=25 Jared (Guest)
on 2006-12-22 02:04
(Received via mailing list)
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

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 =[:event])

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

   def service_at=(time)"converting #{time} to UTC")
    time = unless location.nil?"#{time} to be saved.")
    write_attribute(:service_at, time)

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
  project_id: 1
  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 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 method isn't making the
location object available to it's newly created association?

This topic is locked and can not be replied to.