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

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

+7
ruby ruby-on-rails activerecord
source share
2 answers

Both of them are just methods to get to the attribute - they are both just getters. self.attribtue is a more โ€œtraditionalโ€ getter, while self[:attribute] is basically just a [] method. Switching between use either has no effect.

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

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

+9
source share

There is a key difference that skips the accepted answer. If you are trying to change the attribute when setting the value , then you should use self[:attribute] .

For example...

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

This will not work because it is self-regulation (you will get a "too deep stack" error). Instead, you should assign a value by doing ...

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

There is also a named method write_attribute , which performs the same actions 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 that I actually define is variable, for example.

 write_attribute(var, 'some value') 
+2
source share

All Articles