使用 SQL 函数更新 ActiveRecord 属性

dda*_*son 2 ruby mysql ruby-on-rails ruby-on-rails-4

在 rails 中,您是否能够通过对 SQL 函数的评估来更新记录的属性?

MySQL表

| time_started        | time_to_execute |
|---------------------------------------|
| 2015-10-28 14:13:58 |      NULL       |
Run Code Online (Sandbox Code Playgroud)

我正在尝试做的事情:

update table set time_to_execute = TIME_TO_SEC(TIMEDIFF(NOW(), time_started))
Run Code Online (Sandbox Code Playgroud)

通过一个模型。


我尝试使用通用属性更新方法来做到这一点,但无济于事。

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))'})
Run Code Online (Sandbox Code Playgroud)

是否可以使用 SQL 函数更新 ActiveRecord 模型的属性?

我知道我可以执行任意 SQL 或计算两个DateTimeruby 对象之间的差异,但我想知道这是否可以通过模型方法实现。

Wiz*_*Ogz 6

您可以使用它#update_all来执行此操作

c.class.where(id: c.id).update_all("time_to_execute = TIME_TO_SEC(TIMEDIFF(NOW(), time_started))")
Run Code Online (Sandbox Code Playgroud)

请注意,您可以替换c.class为模型的实际类名(当前未显示在答案中)。

更新以显示原始 SQL 实现

c.class.connection.execute "update table set time_to_execute = TIME_TO_SEC(TIMEDIFF(NOW(), time_started)) WHERE id = #{ c.id }"
Run Code Online (Sandbox Code Playgroud)