I am currently using helpers to format the display of attributes, but I
would like to control the format of the attribute values when
populating a text field and also when the model instances are populated
from params once the user submits.
I’ve been fooling around with overriding attributes in the model, but
either I am missing something or heading down the wrong path.
I am currently using helpers to format the display of attributes, but I
would like to control the format of the attribute values when
populating a text field and also when the model instances are populated
from params once the user submits.
I’ve been fooling around with overriding attributes in the model, but
either I am missing something or heading down the wrong path.
Any guidance would be greatly appreciated.
Thanks,
Dan
A helper is the “right” way to do it, since the model should simply now
about its values, and the view should descide how to render those
values.
However, you can simply create a method with the same name as the
column, or a new name that references that column.
Here is an example that stores a price as an integer in the database,
tracking pennies instead of dollars. The rails app should deal with
floats from the setters and getters of the price column. This way “995”
is stored in the database, but @product.price yields “9.95”. Simply
override the price and price= methods, and use self[:price] to access
the original raw attribute value.
class Product
# convert pennies to dollars
def price
self[:price].to_f / 100
end
# convert assigned price to pennies
def price=(value)
self[:price] = (value * 100).to_i
end
# return a string with a $
def formatted_price
"$#{price}"
end
A helper is the “right” way to do it, since the model should simply now
about its values, and the view should descide how to render those
values.
Hi Alex,
Thanks for the response. I am using a helper for general display of
attributes, but I need to mask the display of attributes in and out of
text fields. Is there a way to accomplish this with helper style code
or do I need to work with the model like your example outlined?
Thanks for the response. I am using a helper for general display of
attributes, but I need to mask the display of attributes in and out of
text fields. Is there a way to accomplish this with helper style code
or do I need to work with the model like your example outlined?
By ‘mask’ are you talking about format restrictions ?
Like that phone number field must be xxx-xxx-xxxx ?
Alan
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.