Topher Fangio
Topher Fangio

Reputation: 20667

Rails/PostgreSQL - Locking rows based on attribute?

I have a generate method in one of my controllers that creates, updates and possibly destroys some ListColumns and ListCells, both of which have a list_id that points back to the original List. I need to ensure that the ListColumns won't change while I'm creating the ListCells.

However, since generating the data might take a while, if a separate user calls generate on a different list, I'd like it to go ahead and create the ListColumns and ListCells for that list.

So, is there a way to lock the table so that I can't add a ListColumn with a particular list_id until after the transaction is completed?

Thanks so much!

Upvotes: 0

Views: 231

Answers (1)

araqnid
araqnid

Reputation: 133412

Use the list table rows themselves as locks. Simply select a row from list in exclusive mode:

select list.list_id from list where list.list_id = ? for update

Even if you're not going to actually update that row, doing that at the start of your method will block any other executions with the same list_id

Upvotes: 2

Related Questions