How to lock multiple resources in RoR

When I tried to lock multiple records at one time, I noticed that the doc of Rails didn’t notice it.

accounts = Account.where(...)
account1 = accounts.detect { |account| ... }
account2 = accounts.detect { |account| ... }

I wanted to lock detected accounts without getting each one. However, I managed to do that in the project I’m belonging to.

How can we lock multiple records?

ActiveRecord::Base.transaction do
locked_accounts = Account.where(
id: ids,
).lock
locked_accounts.save!
end
end

We can do like this.

Feel free to reach out to me on LinkedIn, which you can find below. Looking forward to connecting!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

--

--

Tomoharu Tsutsumi
Tomoharu Tsutsumi

Written by Tomoharu Tsutsumi

Senior Software Engineer at two industry-leading startups ( Go | Ruby | TypeScript | JavaScript | Gin | Echo | Rails | React | Redux | Next)

No responses yet