現在,如果我非常快速地粉碎這個「銷售」按鈕,以便html沒有時間更新,我可以連續銷售相同的物品並獲得每次點數,我該如何防止這種情況?防止快速按鈕砸
方法用戶模型:
has_many :drivers
def withdraw(amount)
balance = self.credit
if balance >= amount
new_balance = balance - amount
self.update credit: new_balance
true
else
false
end
end
def deposit(amount)
balance = self.credit
balance += amount
self.update credit: balance
end
def purchase(package)
cost = package.cost
ActiveRecord::Base.transaction do
self.withdraw(cost)
package.update user_id: self.id
end
end
def sell(package)
cost = package.cost
ActiveRecord::Base.transaction do
self.deposit(cost)
package.update user_id: nil
end
end
視圖,買入/賣出按鈕:
<% unless @driver.owned? %>
<%= button_to "Buy", purchase_driver_path %>
<% else %>
<%= button_to "Sell", sell_driver_path, method: :delete %>
<% end %>
我的控制器
class DriversController < ApplicationController
def show
@user = current_user
@driver = Driver.find(params[:id])
end
def purchase
@driver = Driver.find(params[:id])
@user = current_user
if @user.purchase(@driver)
flash[:succes] = "Purchase succesful!"
else
flash[:error] = "Error"
end
render "show"
end
def sell
@driver = Driver.find(params[:id])
@user = current_user
if @user.sell(@driver)
flash[:succes] = "Sell succesful!"
else
flash[:error] = "Error"
end
render "show"
end
end
謝謝!
您好,感謝您的回覆,但可能只是人們解釋「!user_id_change [0] == nil」測試的內容?然後,「package.update user_id:self.id」然後是「package.user_id = self.id package.save(context::purchase)」 – manis
!user_id_change [0] == nil應該是什麼區別user_id_change [0]!=無 – Woahdae
這是說「如果ID從一個ID更改爲另一個,這是無效的」。 user_id_change是一個動態定義的方法,它返回[from-value,to-value]的數組。請參閱「活動記錄髒對象」文檔(在我的手機上,或者我會鏈接到它) – Woahdae