Rails: Increament in a datetime column in all tables

牧云@^-^@ 提交于 2019-12-24 18:52:16

问题


Lets say I have 20 tables and every table has column updated_at I want to update all the rows in all the tables such as every row's updated_at field should increase 1 hour. How can I do it with avoiding to update active records object I would prefer to run a sql query instead on every table one query for one table.


回答1:


If you ask this question in the database admin section of SO I think you'll get a much better response.

I tried googling and can find:

https://www.w3schools.com/sql/func_sqlserver_dateadd.asp

SELECT DATEADD(month, 2, '2017/08/25') AS DateAdd;

So in your case, if it's called updated_at and the table is users:

SELECT UpdatedAt, DATEADD(hour, 1, UpdatedAt) AS DateAdd FROM Employees;

I'm pretty crap at SQL but I think that should make sense.

If it doesn't work, repost this to the database section and you'll have people who know what they're talking about helping you :)




回答2:


You can accomplish this via the Rails console without actually instantiating the ActiveRecord objects if you use update_columns

You should be able to do:

YourThing.find_each do |thing|
  new_time = thing.updated_at + 1.hour
  thing.update_columns(updated_at: new_time)
end

That will bypass validation and all callbacks, so it should run pretty quickly, depending on the number of records you're working with.

Here's the documentation for update_columns: https://apidock.com/rails/ActiveRecord/Persistence/update_columns




回答3:


just to help others here is how was I able to get this solve

ActiveRecord::Base.connection.execute("UPDATE users SET created_at = created_at + INTERVAL '3600 seconds'")


来源:https://stackoverflow.com/questions/55181871/rails-increament-in-a-datetime-column-in-all-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!