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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -