简体   繁体   中英

Rails update_all from associated_object

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 ?

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.find_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

You can use touch method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM