Toshi Toshi - 5 months ago 71
Ruby Question

Ruby Active Record accessor dot(.) vs bracket([])

With Active Record, we can access a value like

method access

user = User.find(1) #=> 'John'


hash access

user[:name] #=> 'John'

I just wonder when to use which, or is there any best practice out there?
Personally I'd prefer
method access
because I feel that is more like ruby way. However when I see code by others, I face the
hash access


Rails convention is to use ActiveRecord::AttributeMethods::Read#read_attribute (dot notation), rather than its alias ActiveRecord::AttributeMethods#[], which:

Returns the value of the attribute identified by attr_name after it has been typecast (for example, “2004-12-12” in a date column is cast to a date object, like, 12, 12)). It raises ActiveModel::MissingAttributeError if the identified attribute is missing.