Reputation: 1399
I am making an app in which users place bets on future scenarios like "Who Will Win American Idol?"
The user places his bet (referred to in the code as a prop).
Then later, the admin chooses the correct answer by editing the answer of the bet.
I want then, to check in the database to see whether the answer that each user has matches the answer that the admin has just provided.
I am trying to do something like this
def update
@user = User.find(session[:user_id])
@prop = Prop.find(params[:id])
@answer = Answer.find(params[:id])
@prop.update(prop_params)
User.all.map
{ |user|
#the code here is called once for each user
# user is accessible by 'user' variable
if @answer.choice == @prop.choice
puts "hello"
@user.score += 7
@user.save
else
@user.score -= 7
@user.save
end
}
end
What is the best way to accomplish my goal?
Upvotes: 0
Views: 89
Reputation: 6707
It should be simply like this:
def update
@user = User.find(session[:user_id])
@prop = Prop.find(params[:id])
@answer = Answer.find(params[:id])
@prop.update(prop_params)
score_change = @answer.choice == @prop.choice ? 7 : -7
User.update_all("score = score + #{score_change}")
end
Explanation
This will return 7 or -7 as you want
score_change = @answer.choice == @prop.choice ? 7 : -7
Then we just update all user in a single query, don't need to iterate over each of user
User.update_all("score = score + #{score_change}")
Under the hook, this sql will be generated:
UPDATE "users" SET score = score + 7
Or
UPDATE "users" SET score = score + -7
Upvotes: 1