开发者

Updating a counter in Rails, does this have concurrency issues?

开发者 https://www.devze.com 2023-03-31 00:46 出处:网络
Say I allow people to vote on items, and I am doing this: bid = Bid.new .. bid.save! item.tota开发者_JS百科l_bids += 1

Say I allow people to vote on items, and I am doing this:

bid = Bid.new
..
bid.save!


item.tota开发者_JS百科l_bids += 1
item.save!

Won't this have issues if multiple people are biding on an item at the same time?


Absolutely it can have concurrency issues. Rails provides increment_counter to handle this:

Item.increment_counter( :total_bids, item.id )

This runs the SQL on the database:

UPDATE items SET total_bids = total_bids + 1 WHERE id = x

See here for more details: http://api.rubyonrails.org/classes/ActiveRecord/CounterCache.html#method-i-increment_counter


If you are using Sidekiq or a have a .delay method with some similar job queue try this:

Item.delay.increment_counter(:total_bids, item.id)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号