【问题标题】:Undefined method `update_attributes'?未定义的方法“update_attributes”?
【发布时间】:2014-01-27 21:43:24
【问题描述】:

为什么会出现此错误?我没有想法。

undefined method `update_attributes' for #

代码:

exists = Vote.where(comment_id: @comment.id).exists?
    if exists
        update_vote = Vote.where(comment_id: @comment.id)
        update_vote.update_attributes(value: 5)
        redirect_to :back
    else

【问题讨论】:

  • 此错误消息告诉您的是您的update_vote.update_attributes 未定义。在你的代码前面的某个地方,你应该定义update_attributes,否则你不能在这里使用它。

标签: ruby-on-rails mongodb ruby-on-rails-4 mongoid


【解决方案1】:

你特别想获取一条记录,所以告诉它:

update_vote = Vote.where(comment_id: @comment.id).first

但是如果没有匹配,这段代码很容易出错,小心。

【讨论】:

    【解决方案2】:

    尝试使用find_by 而不是where。它将返回一个文档而不是Mongoid::Criteria,这就是您收到该错误的原因(您尝试运行.update_attributes,它作用于单个记录,一组记录)。请考虑以下内容。

    if update_vote = Vote.find_by(comment_id: @comment.id)
      update_vote.update_attributes(value: 5)
      redirect_to :back
    else
    

    上面的代码还可以避免对.exists?的不必要调用,因为存在性检查与定义是正确的(如果.find_by没有找到任何匹配的记录,它返回nil,很像.where(...).first也可以)。

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多