开发者

What's difference between instance_name[:column_name] and instance_name.column_name?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜