Rails - 如何正确转义 update_all 查询中的值

Rails - How to properly escape values in a update_all query

所以我有一个 update_all 查询,如下所示:

Task.where(...).update_all('position = position - X, parent_id = Y')

我想用整数值替换 X 和 Y。我想安全地进行:"the rails way"。 知道如何实现吗?


编辑:我的 rails 控制器中没有位置变量。如果 X = 1,最终查询应按字面意思包含 "position=position-1".

此外,update_all documentation 指定此方法仅接受一个参数:表示 SQL 语句的 SET 部分的字符串、数组或散列。


编辑 2:好的,我通过稍微调整 Arup Rakshit 解决方案让它工作。这是最终的工作解决方案:

Task.update_all(['position = position - ?, parent_id = ?', X, Y])

写成:

Task.where(...)
    .update_all(['position = ?, parent_id = ?', position - X, Y])

阅读update_all

conditions - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro for more info.

演示:

Loading development environment (Rails 4.2.0)
[1] pry(main)> Person.pluck(:name, :email)
   (0.4ms)  SELECT "people"."name", "people"."email" FROM "people"
=> [["xxxx", nil], ["xxxx", nil], ["xxxx", nil]]
[3] pry(main)> Person.where(email: nil).update_all ["name = ?, email = ?", "foo", "test@test.com"]
  SQL (0.7ms)  UPDATE "people" SET name = 'foo', email = 'test@test.com' WHERE "people"."email" IS NULL
=> 3
[4] pry(main)> Person.pluck(:name, :email)
   (0.3ms)  SELECT "people"."name", "people"."email" FROM "people"
=> [["foo", "test@test.com"], ["foo", "test@test.com"], ["foo", "test@test.com"]]
[5] pry(main)>

尝试这样做:

Task.where(...).update_all("position = ?, parent_id = ?",position - X, Y )