Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails override attribute using his getter

I have a price attribute in my model.

Can I use attribute-getter, which is named just like the attribute

def price
   ... logic logic ..
   return something
end

in order to override the attribute itself ?

Currently it doesn't work. If I call model.price it works, but when it somes to saving the object via model.save, it stores the default value.

Can it be done in a painless way, or should I make a before_save callback?

like image 674
Dmitri Avatar asked Dec 06 '25 09:12

Dmitri


2 Answers

If you set a value in Ruby you access the setter method. If you want to override the setter you have to do something like this:

def price=(_price)
  # do some logic
  write_attribute(:price, _price)
end

This is of course a discussion point. Sometimes you can better use a callback. Something like this:

before_save :format_price

private

def format_price
  # Do some logic, for example make it cents.
  self.price = price * 100
end
like image 135
Michael Koper Avatar answered Dec 08 '25 22:12

Michael Koper


Since you seem to want the "real" value stored in the database, what you probably want to do is modify the setter. This way the actual value is stored, and the price getter can just return it unmodified.

You can do this via the lower level write_attribute method. Something like:

def price=(value)
  # logic logic
  self.write_attribute(:price, value)
end
like image 42
numbers1311407 Avatar answered Dec 08 '25 23:12

numbers1311407