I'm new to Rails. I found that the 2 ways below get the same result, but I can't understand the code.
[ ]
should be the operator for array, right? Why can I use it in the following way:
code 1:
drummer = Drummer.find(1)
drummer[:name]
=>"Jojo Mayer"
code 2:
drummer = Drummer.find(1)
dr开发者_如何学运维ummer.name
=> "Jojo Mayer"
There is no difference. ActiveRecord:Base instance method [] just calls read_attribute which returns the same value.
The purpose of the [] method is to allow passing the attribute name with a variable, e.g.:
key = :name
drummer[key]
=>"Jojo Mayer"
Actually there is an important difference.
If you need to do some sort of processing on the value by overriding the setter:
class Drummer
def name= value
self[:name] = value.capitalize
end
end
Then drummer[:name] allows you to bypass the override.
精彩评论