[英]How Do I Update Two Models in Rails Simultaneously?
假設我有一個將兩個人匹配的應用程序,有點像“熱與不熱”。
我有我的matchup視圖,可將隨機用戶從數據庫中拉出並相互匹配。 當用戶為某人投票時,我想將他們的:wins
和:matches_played
增加1,但我也想將失敗者:matches_played
增加1,以便我可以計算排名。
有沒有一種方法可以為每個人使用表格來完成此任務,或者我是否需要一個介於兩者之間的模型,例如Match,其中有兩列分別代表獲勝者和失敗者,如果可以的話,這將如何工作。
僅使用People模型(“簡單”方式)執行此操作:
假設您有以下路線:
new_person GET /people/new(.:format) {:action=>"new", :controller=>"people"}
edit_person GET /people/:id/edit(.:format) {:action=>"edit", :controller=>"people"}
person GET /people/:id(.:format) {:action=>"show", :controller=>"people"}
PUT /people/:id(.:format) {:action=>"update", :controller=>"people"}
DELETE /people/:id(.:format) {:action=>"destroy", :controller=>"people"}
HAML版本的視圖代碼:
- # Person A form
= form_tag(person_path(@personA, :loser_id => @personB), :method => :put) do
= submit_tag "Vote for Person A"
- # Person B form
= form_tag(person_path(@personB, :loser_id => @personA), :method => :put) do
= submit_tag "Vote for Person B"
ERB版本:
<%# Person A form %>
<% form_tag(person_path(@personA, :loser_id => @personB), :method => :put) do %>
<%= submit_tag "Vote for Person A" %>
<% end %>
<%# Person B form %>
<% form_tag(person_path(@personB, :loser_id => @personA), :method => :put) do %>
<%= submit_tag "Vote for Person B" %>
<% end %>
然后在您的控制器中執行update
操作:
def update
People.transaction do
winner = People.find(params[:id])
loser = People.find(params[:loser_id])
# Increment the winner
winner.increment! :matches_played
winner.increment! :wins
# Increment the loser
loser.increment! :matches_played
end
respond_to do |format|
format.html { redirect_to new_match_path }
end
end
正如有人在評論中指出的那樣,您應該將其包裝在所謂的事務中,這樣,如果事務中的所有內容都成功保存,它就將永久存在於數據庫中。
即使我向您展示了上述方法,我仍然建議您使用Match
模型。 最終,使用這個額外的模型將幫助您驗證以下內容,以便人們無法對您的系統進行游戲。
是的,這一切都需要更多的工作(這就是為什么我沒有為它顯示代碼),但如果你擔心上述任何一個問題,它可能是你想做的事情。
您應該編寫表單提交,以將兩個用戶ID提交給您的控制器,並指示獲勝用戶。 然后你可以對它們進行操作並將它們保存到db。
winner = People.find(params[:winner_id])
loser = People.find(params[:loser_id])
winner.matches_played += 1
winner.wins += 1
loser.matches_played += 1
winner.save!
loser.save!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.