I have a model where I want to change the display for a single attribute such that if the value is an integer, it displays with no decimal point (e.g. "1"), but if it is non-integer, it displays with a decimal point (e.g. "1.25"). The easiest way to do this seems to be if I could override the to_string method for my_model.my_attribute.to_s. Is there a way to do this? Or a better way altogether? thanks, Jeff -- Posted via http://www.ruby-forum.com/.
On Friday, July 14, 2006, at 9:46 PM, Jeff Cole wrote:>I have a model where I want to change the display for a single attribute >such that if the value is an integer, it displays with no decimal point >(e.g. "1"), but if it is non-integer, it displays with a decimal point >(e.g. "1.25"). > >The easiest way to do this seems to be if I could override the to_string >method for my_model.my_attribute.to_s. Is there a way to do this? Or >a better way altogether? > >thanks, >Jeff > >-- >Posted via http://www.ruby-forum.com/. >_______________________________________________ >Rails mailing list >Rails@lists.rubyonrails.org >http://lists.rubyonrails.org/mailman/listinfo/railsoverride the attribute method on your model and have it return the formatted value. _Kevin -- Posted with http://DevLists.com. Sign up and save your mailbox.
How do you do that without making it recursive? For example #override method for attribute foo def foo return format(foo) end -jeff> override the attribute method on your model and have it return the > formatted value. > > _Kevin-- Posted via http://www.ruby-forum.com/.
Jeff Cole wrote: >> override the attribute method on your model and have it return the>> formatted value. >> >> _Kevin> How do you do that without making it recursive? For example > > #override method for attribute foo > def foo > return format(foo) > end > > -jeff You can use read_attribute for this. eg the example from the documentation: class Song < ActiveRecord::Base # Uses an integer of seconds to hold the length of the song def length=(minutes) write_attribute(:length, minutes * 60) end def length read_attribute(:length) / 60 end end http://api.rubyonrails.org/classes/ActiveRecord/Base.html under ''Overwriting default accessors'' hth -- R.Livsey http://livsey.org
Maybe Matching Threads
- when to set a class attribute variable during boot
- ActiveRecord override
- How do I stop a column being updated by model.save?
- Overriding AR read/write_attribute - Overridden write_attribute Is Never Called
- Delaying initialization of associations until first access