Rails 3: Fetching a pre-generated value from a related model
I have an app where the client will provide a list of pre-generated codes. When someone purchases a license, one of these codes will be served up.
There is a Product
model that has_many :codes
, and a Code
model that belongs_to :product
. The code model has a state
which is either "assigned" or "unassigned".
How do I ensure that each code gets used only once, even if multiple processes are trying to fetch it? In the bad old days, I would lock the record, and if I couldn't开发者_高级运维 lock it, move to the next one, but I'm not even sure I can do something like that in Rails.
The "bad old days" where ACID existed are still today. Read more on Rails/AR's locking on railsguides.
Item.transaction do
i = Item.lock("LOCK IN SHARE MODE").find(id)
# get rollin
i.save!
end
精彩评论