代码之家  ›  专栏  ›  技术社区  ›  O.Don

尝试在rails中实现非常简单的点

  •  1
  • O.Don  · 技术社区  · 6 年前

    在我的控制器中看到以下代码

    def create
            @wad = current_user.wads.build(wad_params)
            if @wad.save
                current_user.points == current_user.points + 5
                redirect_to @wad    
            else
                flash[:error] = 'Error try again'
                render 'new'
            end
        end
    

    我的目标是,当用户创建一个wad时,他们会得到5分。我很好地将points列迁移到了用户表中,并且能够通过控制台更新点。

    我根本没有得到任何错误,wad像往常一样被创建,页面重定向正确,但是points值没有在user表中被更新。有什么问题吗?

    1 回复  |  直到 6 年前
        1
  •  3
  •   SRack    6 年前

    这里有两点:

    首先,改变你的 user 因为你没有保存任何一条记录,所以暂时不会保留。

    另外,您还需要使用 = 分配用户的 points ,或以下示例中的方法。以下代码将克服此问题:

    def create
      @wad = current_user.wads.build(wad_params)
      if @wad.save
        current_user.update_attributes(points: current_user.points + 5) # update_attributes assigns the attributes and saves
        redirect_to @wad    
      else
        flash[:error] = 'Error try again'
        render 'new'
      end
    end