Updating a counter in Rails, does this have concurrency issues?
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)
精彩评论