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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With