2016-03-18 17 views
1

kontrolörRoR'da paralel erişim nasıl engellenir?

can_buy = nil 
if game.spot_price == 0 
    return {json: {error: 1, error_message: "You can do it only once"}, status: 400} if game.spots.where(user_id: user.id).length > 0 
    can_buy = true 
else 
    can_buy = UserService.have_enough_money?(user, game.spot_price) 
end 
if can_buy 
    ActiveRecord::Base.transaction do 
     # purchase goes here 
    end 
end 

yoktur Ve kullanıcı aynı anda birkaç istekte ve spot_price 0 ise, o birkaç kez satın alabilirsiniz, ama sadece bir kez yapabilirsiniz. Nasıl önlenir? P.S. .: üzgün için ingilizcem

+1

_Sidenote_: 'can_buy = nil' gereksiz olduğunu. “if” operatörü iç içe kapsamı tanımlamaz. – mudasobwa

cevap

2
önceki bir işlem başlatın

:

if game.spot_price.zero? && game.spots.where(user_id: user.id).length > 0 
    return json: {error: 1, error_message: "You can do it only once"}, 
     status: 400 
end 
ActiveRecord::Base.transaction do 
    if game.spot_price.zero? || UserService.have_enough_money?(user, game.spot_price) 
    ... 
    else 
    raise ActiveRecord::Rollback, "Not permitted!" 
    end 
end