Rails ActiveRecord - How to set association save order
- by Altonymous
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