【问题标题】:Rails - How do i update a records value in a join model?Rails - 如何更新连接模型中的记录值?
【发布时间】:2011-01-07 18:11:44
【问题描述】:

我在 HABTM 关系中有一个连接模型,具有直通关联(详情如下)。我正在尝试查找记录....找到该记录属性的值...更改值并更新记录,但很难做到这一点。

模型设置是这个>>

用户.rb

 has_many :choices
 has_many :interests, :through => :choices

利息.rb

 has_many :choices
 has_many :users, :through => :choices

Choice.rb

 belongs_to :user
 belongs_to :interest

Choice 有 user_id、interest_id、score 作为字段。

然后我找到了 ?object?像这样>>

@choice = Choice.where(:user_id => @user.id, :interest_id => interest.id)

所以模型 Choice 有一个名为 :score 的属性。如何找到 score 列的值....并将其 +1/-1 然后重新保存?

我试过了

 @choice.score = @choice.score + 1 
 @choice.update_attributes(params[:choice])
 flash[:notice] = "Successfully updated choices value."

但我得到“未定义的方法分数”......我错过了什么?

【问题讨论】:

  • 检查!可能是你得到了@choice 的数组。

标签: ruby-on-rails


【解决方案1】:

您可能需要使用.first 来运行实际查询并返回结果:

@choice = Choice.where(:user_id => @user.id, :interest_id => interest.id).first

...否则@choice 只保存一个活动关系对象...它还没有执行查询。

【讨论】:

    【解决方案2】:

    您的查询将返回一系列选择,因此您需要指定 .first 以获取要更新的实际模型。在更新之前,请务必检查您是否真的持有任何对象,这样您就不会尝试更新 nil :)

    此外,如果您只想增加或减少一个字段,那么您可以使用 .increment 方法!或.递减!这将立即更新到数据库。

    @choice.increment!(:score)
    

    因为在您的情况下,如果 params[:choice] 包含一个分数值,它将覆盖您之前分配的值。

    【讨论】:

      【解决方案3】:

      你已经有了@user 对象,所以使用它:

      @choice = @user.choices.find_by_interest_id(interest.id)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-17
        • 2012-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-21
        • 1970-01-01
        相关资源
        最近更新 更多