1

In Rails 6.1 I would like to select a relation for update (lock the rows inside a transaction).

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

In previous versions of rails, I think this could be hacked with foos_query.lock.pluck(''), but it stopped working at some point.

Is there a supported or hacky way to do this without raw sql?

related:

John Bachir
  • 22,495
  • 29
  • 154
  • 227

1 Answers1

0

I went with

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

see also

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

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

John Bachir
  • 22,495
  • 29
  • 154
  • 227