I am trying to update several rows in a table which match some criteria (ie. all rows where some_col = “foo”). I want do this update as part of a transaction wherein I acquire a lock in share mode on all these rows, update row by row, and release the shared locks.
The documentation I have read so far talks about how to lock individual rows in ActiveRecord. But this will make things inefficient since I will have to first perform some .where(…) query, iterate through each row, and lock it (which refetches the row from the db). So I will be two db fetches per row…
I was wondering what is the best way to lock all rows which match a certain criteria in the .where(…) query itself. Is this possible? If not, are there better ways of locking a certain set of rows more efficiently. Locking the table is not an option.
Thanks!
Try this
http://guides.rubyonrails.org/active_record_querying.html#pessimistic-locking
I we assume that your model is
Itemlike in the example, do something like:e.t.c. and build the select you want so that you bring all the rows in a big view/result.
This might be what you want.