Let's say I have this model named Product with a field named brand. Suppose the values of brand are stored in the format this_is_a_brand. Can I define a method in the model (or anywhere else) that allows me to modify the value of brand before it is called. For example, if I call @product.brand, I want to get This is a Brand, instead of this_is_a_brand.
I would recommend using the square bracket syntax ([]
and []=
) instead of read_attribute
and write_attribute
. The square bracket syntax is shorter and designed to wrap the protected read/write_attribute methods.
def brand
original = self[:brand]
transform(original)
end
def brand=(b)
self[:brand] = reverse_transform(b)
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