mysql - 使用 SQL 函数更新 ActiveRecord 属性

标签 mysql ruby-on-rails ruby ruby-on-rails-4

在 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/

相关文章:

php - mysqli_real_escape_string 和双引号问题

mysql - 在 2 个日期/日期时间之间获取结果的复杂查询

ruby-on-rails - 如何使用主动支持核心分机日期和时间

ruby-on-rails - Rails 3 - 权限错误和奇怪的 TypeError

css - 如何覆盖事件管理 CSS?

ruby-on-rails - Controller 方法#show 被调用

mysql - 未找到具有不变名称 'MySql.Data.MySqlClient' 的 ADO.NET 提供程序的 Entity Framework 提供程序。在生成 View 时

php - 如何将变量从 Swift 传递到 PHP 以用于 mySQL 查询?

ruby-on-rails - Rubocop JSON : Align the parameters of a method call if they span more than one line

ruby - 在 ruby​​ 中使用 Queue 类与使用数组实现队列之间的区别