Why won't write_attribute(:price, value*100) work in the console?

Hi,

I’m confused as to why this code example (from a book) won’t work.
They want to store a price in cents, but be able to set it and query it
in Euros. To this end they are overwriting the getter and setter
methods.

In my model:

class Product < ActiveRecord::Base
def price
Product.read_attribute(:price)/100.0
end
def price=(value)
Product.write_attribute(:price, value*100)
end
end

In the console:
r = Product.new
=> #<Product id: nil, name: nil, price: nil, enabled: true, created_at:
nil, updated_at: nil>

r.price = 10
NoMethodError: undefined method `write_attribute’ for #Class:0x6182658

There is no mention of a typo in the book’s errata, write_attribute
doesn’t appear to have been removed from rails, so I’m guessing
something changed with rails which makes this not work.

I did some googling and saw that shorthand for read/write_attribute() is
self[]

I tried the following and it worked great:

class Product < ActiveRecord::Base
def price
self[:price]/100.0
end
def price=(value)
self[:price] = value*100
end
end

r = Product.new
=> #<Product id: nil, name: nil, price: nil, enabled: true, created_at:
nil, updated_at: nil>

r.price = 10
=> 10

Could anyone tell me why the first example produces a NoMethodError and
the second one works just fine?

Thanks very much.

On Jan 14, 3:39pm, Jim B. [email protected] wrote:

Could anyone tell me why the first example produces a NoMethodError and
the second one works just fine?

because read/write_attribute are instance methods, but you’re trying
to call them on Product (ie a class). self.read_attribute (or just
read_attribute) should work fine

Fred

Cheers Fred,

That was actually embarrassingly obvious.
Thanks for your help.