Rails, activerecord: self[:attribute] vs self.attribute

后端 未结 2 1511
囚心锁ツ
囚心锁ツ 2021-01-02 04:29

When accessing active record column/attributes in rails, what is the difference between using self[:attribute] vs self.attribute? Does this affect getters and setters?

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 04:48

    There's a key difference that the accepted answer misses. If you are attempting to modify the attribute while setting the value, then you must use self[:attribute].

    For example...

    def some_attr=(val)
      self.some_attr = val.downcase   # winds up calling itself
    end
    

    This won't work, because it's self-referencing (you'll get a "Stack too deep" error). Instead you must assign the value by doing...

    def some_attr=(val)
      self[:some_attr] = val.downcase
    end
    

    There's also a named method write_attribute, which performs the same action as self[:attribute]. Both do what you need, it's a matter of coding style and personal preference. I like write_attribute when the attribute I'm actually defining is variable, e.g.

    write_attribute(var, 'some value')
    

提交回复
热议问题