开发者

Rails 3: Fetching a pre-generated value from a related model

开发者 https://www.devze.com 2023-02-14 10:04 出处:网络
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.

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
0

精彩评论

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