简体   繁体   English

更新Rails数据库中的所有记录

[英]Update All Records in Rails Database

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? 实现目标的最佳方法是什么?

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 您将根据需要返回7或-7

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: 在钩子下,将生成此sql:

UPDATE "users" SET score = score + 7

Or 要么

UPDATE "users" SET score = score + -7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM