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?
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')