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?
self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.
self is a reserved keyword in Ruby that always refers to the current object and classes are also objects, but the object self refers to frequently changes based on the situation or context. So if you're in an instance, self refers to the instance. If you're in a class, self refers to that class.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With