1

Could someone explain the difference between these two:

Say I have a model Product

inside that model I have:

self.price
self[:price]

I'm assuming one calls an attribute (the products price), while the other calls a method named 'price'?

If that's true, which is which?

Brad
  • 8,044
  • 10
  • 39
  • 50

2 Answers2

4

Both calling a method:

  • first one calls a method :price.

  • second one calls a method :[], passing :price as an argument.

You can check that by running

self.method(:[])
#=> #<Method: User(ActiveRecord::AttributeMethods)#[]>

Basically anytime you want to know, where method comes from, you can use Object#method.

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
0

Rails creates those model attributes as accessors which dynamically creates the methods for getting/setting the value. Its fun to use in your own classes as well, have a look here: http://ruby-doc.org/core/Module.html#method-i-attr_accessor

Derek Wright
  • 1,452
  • 9
  • 11
  • So if I create my own method with the same name as an attribute, my method gets called not the rails default? – Brad May 09 '17 at 13:12
  • Here's a post that details how you might want to accomplish that: http://stackoverflow.com/questions/373731/override-activerecord-attribute-methods – Derek Wright May 09 '17 at 13:14