【问题标题】:Is there any way to select an ActiveRecord relation for update?有没有办法选择一个 ActiveRecord 关系进行更新?
【发布时间】:2021-12-02 16:26:36
【问题描述】:

在 Rails 6.1 中,我想选择一个关系进行更新(锁定事务中的行)。

Foo.transaction do
  # this is foos_query in raw sql
  ActiveRecord::Base.connection.execute <<~SQL
    SELECT FROM "foos"
    WHERE
      type = 'bar' AND
      associated_object = '#{thing_id}' AND
      other_party_id = '#{user_id}'
    ORDER BY id
    FOR UPDATE
  SQL
  foos_query.update_all(read: "true", seen: true)
end

在以前的 Rails 版本中,我认为这可能会被 foos_query.lock.pluck('') 破解,但它在某个时候停止工作。

在没有原始 sql 的情况下,是否有一种受支持或 hacky 的方式来做到这一点?

相关:

【问题讨论】:

标签: sql ruby-on-rails activerecord


【解决方案1】:

我去了

ActiveRecord::Base.connection.execute foos_query.order(:id).lock.to_sql

另见

https://dba.stackexchange.com/questions/257188

https://dba.stackexchange.com/questions/257217

【讨论】:

    猜你喜欢
    • 2010-10-04
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 2013-07-12
    • 1970-01-01
    相关资源
    最近更新 更多