在 Rails 中,您是否能够通过 SQL 函数的评估来更新记录的属性?
MySQL 表
| time_started | time_to_execute |
|---------------------------------------|
| 2015-10-28 14:13:58 | NULL |
我正在尝试做的事情:
update table set time_to_execute = TIME_TO_SEC(TIMEDIFF(NOW(), time_started))
通过一个模型。
我曾尝试使用通用属性更新方法来执行此操作,但无济于事。
c.update_attribute(:time_to_execute, 'TIME_TO_SEC(TIMEDIFF(NOW(), time_started))')
c.update({:time_to_execute => 'TIME_TO_SEC(TIMEDIFF(NOW(), time_started))'})
是否可以使用 SQL 函数更新 ActiveRecord 模型的属性?
我知道我可以执行任意 SQL 或计算两个 DateTime
ruby 对象之间的差异,但我想知道这是否可以通过模型方法实现。
最佳答案
您可以使用#update_all
来执行此操作
c.class.where(id: c.id).update_all("time_to_execute = TIME_TO_SEC(TIMEDIFF(NOW(), time_started))")
请注意,您可以将 c.class
替换为模型的实际类名(当前未在答案中显示)。
更新以显示原始 SQL 实现
c.class.connection.execute "update table set time_to_execute = TIME_TO_SEC(TIMEDIFF(NOW(), time_started)) WHERE id = #{ c.id }"
关于mysql - 使用 SQL 函数更新 ActiveRecord 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33394132/