Home > Blockchain >  Rails update_all from associated_object
Rails update_all from associated_object

Time:05-16

I have a Glass object and a Prescription object, but i forgot to add timestamps to the Glass Object, so i created a migration to do that. However, not surprisingly all the objects have todays date and time.

glass belongs_to :prescription prescription has_one :glass

However, I can get the correct timestamp from the Prescription object. I just don't know how to do that. So I want to do something like

Glass.update_all(:created_at => self.prescription.created_at)

any ideas ?

CodePudding user response:

Easiest thing to do is simply multiple SQL queries, it's a one off migration so no biggie I think. ActiveRecord update_all is meant to update the matching records with the same value so that won't work.

Glass.all.each do |glass|
   glass.update!(created_at: glass.prescription.created_at
end

If you want one query (update based on a join - called "update from" in sql terms) it seems not straightforward in ActiveRecord (should work on MySQL but not on Postgres) https://github.com/rails/rails/issues/13496 it will be easier to write raw SQL - this can help you get started https://www.dofactory.com/sql/update-join

CodePudding user response:

You can use touch method

Prescription.find_each do |prescription|
  prescription.glass.touch(:created_at, time: prescription.created_at)
end
  • Related