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

后端 未结 2 1445
囚心锁ツ
囚心锁ツ 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')
    
    0 讨论(0)
  • 2021-01-02 05:14

    They're both just methods to get to the attribute - they're both just getters. self.attribtue is a more "traditional" getter, whereas self[:attribute] is basically just the [] method. Switching between using either has no ramifications.

    I'd recommend using only the self.attribute method because it's syntactically nicer. However, using the self[:attribute] can come in handy when something else overrides the self.attribute method.

    For example, suppose you have a User model with a name database column, so you'd get user.name. But let's say you install a gem that adds a #name method to each of your models. To avoid the complication, one option is to use user[:name] to access it directly without going through the compromised method.

    0 讨论(0)
提交回复
热议问题