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

With an active record, we can access a value of type

method access

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

or

hash access

user[:name] #=> 'John'

I'm just wondering when to use, or is there any best practice out there? Personally, I would prefer method access, because I feel like it is more like a ruby ​​path. However, when I see the code by others, I come across hash access.

+4
source share
2 answers

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

, attr_name typecast (, "2004-12-12" , Date.new(2004, 12, 12)). ActiveModel::MissingAttributeError, .

+4

, .

name, , , - , :

def name "Awesome #{super}!" end

, , , , [], . [], . .

, , , , , " ", . , , . [] .

[] , , , "" , .

0

Source: https://habr.com/ru/post/1661709/


All Articles