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.

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to