【问题标题】:Why the association attribute inside ActiveRecord model cannot be updated without `self`?为什么 ActiveRecord 模型中的关联属性不能在没有 `self` 的情况下更新?
【发布时间】:2013-01-24 19:59:24
【问题描述】:

我定义了一个模型 Item 它是ActiveRecord::Base 的子类 它有一个称为买家的关联属性,它是一个成员

它有一个buy方法来更新buyer属性。

# do buy transaction on that item
def buy(people_who_buy, amount)
  buyer = people_who_buy
  save
  ....
end

此代码无法更新买家属性。 sql生成只对数据库中的成员进行sql选择。

但是在 self. 之前添加 buyer 之后,它工作正常。

# do buy transaction on that item
def buy(people_who_buy, amount)
  self.buyer = people_who_buy
  save
  ....
end

看起来很奇怪!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rails-activerecord


    【解决方案1】:

    在调用 write_accessor 时需要调用 self.write_accessor,而在 self.read_accessor 中,self 可以省略(通常会尽量避免以保持代码干净)。


    来自community-edited ruby styleguide

    在不需要的地方避免使用 self。 (仅在调用 自写访问器。)

    # bad
    def ready?
      if self.last_reviewed_at > self.last_updated_at
        self.worker.update(self.content, self.options)
        self.status = :in_progress
      end
      self.status == :verified
    end
    
    # good
    def ready?
      if last_reviewed_at > last_updated_at
        worker.update(content, options)
        self.status = :in_progress
      end
      status == :verified
    end
    

    【讨论】:

    • 感谢您的回答和示例:) 这是防止名称冲突的方法之一。比如说参数叫buyer,我可以self.buyer = buyer
    【解决方案2】:

    这不仅仅是一个 ActiveRecord 问题。 Ruby 解析器将foo = 123 之类的表达式视为局部变量赋值。为了调用访问器方法,您需要在self.前加上前缀以消除歧义并执行分配方法。

    【讨论】:

    • 感谢您的回答:) 这是防止名称冲突的方法之一。比如说参数叫buyer,我可以self.buyer = buyer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多