Rails ActiveRecord - How to set association save order
Posted
by
Altonymous
on Stack Overflow
See other posts from Stack Overflow
or by Altonymous
Published on 2012-08-07T16:08:23Z
Indexed on
2012/11/12
23:01 UTC
Read the original article
Hit count: 197
I have a weird relationship that needs to be maintained for legacy processes.
I'm trying to figure out how to create the relationship given the new model association.
New Relationship Setup
Machine
has_many MachineReadings
has_many Disks
has_many DiskReadings
Old Relationship Setup
Machine
has_many MachineReadings
has_many DiskReadings
has_many Disks
The problem is data will come in on the Machine model as nested attributes using the new relationship setup. I need to update the machine_reading_id in the DiskReading model so the old association can continue to be used.
I tried doing this via an after_save hook that would traverse back up to the machine and then down to the readings to get the machine_reading.id so I could populate the DiskReading model. However, the associations aren't being saved in the order I would expect. They are saving the Disks & DiskReadings before saving the MachineReadings. So when I go after the machine_reading.id it hasn't been written and thus I am unable to get access to it.
For example:
#machine_disk_reading.rb
after_save :build_old_relationship
def build_old_relationship
self.machine_reading_id = self.disk.machine.readings.find_by_date_time(self.date_time).id
end
© Stack Overflow or respective owner