Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord accessor dot(.) vs bracket([])

With Active Record, we can access a value like

method access

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

or

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.

like image 659
Toshi Avatar asked Nov 23 '16 12:11

Toshi


People also ask

What is the difference between dot notation vs bracket notation?

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.

When should you use dot notation or bracket notation?

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.

Is it more efficient to access properties via dot or square bracket notation?

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.

Why do we use bracket notation?

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.


1 Answers

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 Date.new(2004, 12, 12)). It raises ActiveModel::MissingAttributeError if the identified attribute is missing.

like image 186
Andrey Deineko Avatar answered Sep 23 '22 00:09

Andrey Deineko