Update All Records in Rails Database -
i making app in users place bets on future scenarios "who win american idol?"
the user places bet (referred in code prop).
then later, admin chooses correct answer editing answer of bet.
i want then, check in database see whether answer each user has matches answer admin has provided.
i trying 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 called once each user # user accessible 'user' variable if @answer.choice == @prop.choice puts "hello" @user.score += 7 @user.save else @user.score -= 7 @user.save end } end
what best way accomplish goal?
it should 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 return 7 or -7 want
score_change = @answer.choice == @prop.choice ? 7 : -7
then update user in single query, don't need iterate on each of user
user.update_all("score = score + #{score_change}")
under hook, sql generated:
update "users" set score = score + 7
or
update "users" set score = score + -7
Comments
Post a Comment