With Active Record, we can access a value like
user = User.find(1)
user.name #=> 'John'
or
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
.
Key DifferencesDot notation is faster to write and easier to read than bracket notation. However, you can use variables with bracket notation, but not with dot notation. This is especially useful for situations when you want to access a property but don't know the name of the property ahead of time.
The dot notation is used mostly as it is easier to read and comprehend and also less verbose. The main difference between dot notation and bracket notation is that the bracket notation allows us to access object properties using variable.
In JavaScript, one can access properties using the dot notation ( foo. bar ) or square-bracket notation ( foo["bar"] ). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers.
We must use bracket notation whenever we are accessing an object's property using a variable or when the property's key is a number or includes a symbol or is two words with a space.
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, likeDate.new(2004, 12, 12)
). It raisesActiveModel::MissingAttributeError
if the identified attribute is missing.
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