简体   繁体   中英

Ruby on Rails update database field migration

I try to update all fields of a column with a value from another field. Only when I try + 1 day I get an error.

Workdate is the field that needs to have the new value.

Internal_delivery_date is the column from which the value is derived.

class UpdateWorkdate < ActiveRecord::Migration[5.0]
  def self.up
    Order.update_all(workdate: internal_delivery_date + 1.day)
  end
end

How can I do this without getting an error?

Rails do a lot of silly magic, but it all ends up executing plain old good SQL against the database. Any fancy ActiveRecord::Base#update_all is nothing but a translator to a SQL string. Instead of trying to figure out how to bypass all Rails pitfalls and glitches, I always suggest to use a sledgehammer that never betrays: write SQL and you are all set.

class UpdateWorkdate < ActiveRecord::Migration[5.0]
  def self.up
    Order.connection.execute("
      UPDATE orders
      SET workdate = internal_delivery_date + INTERVAL 1 DAY")
  end
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