Posted by Bob Silva Sat, 22 Apr 2006 08:49:00 GMT
Have a need to track time spent on something? Here's an easy way to allow your users to enter their time in a smart way (anyway they want). This example accepts fractional hours, overflowing minutes and converts and displays them as the user would expect. They are stored in your database as minutes (integer) and displayed as hours/minutes (regardless of how they were input).
Model Code (model.rb):
def set_travel_time(hours, minutes)
self.travel_time = ((hours.to_f * 60) + minutes.to_i).to_i
Controller Code (models_controller.rb):
@model = Model.find(...)
@hours, @minutes = @model.get_travel_time
View Code (_form.rhtml):
<%= text_field_tag 'hours', @hours -%> hours
<%= text_field_tag 'minutes', @minutes -%> minutes
For plugin ideas, see dollars_and_cents: http://blog.codahale.com/2006/05/18/dollars_and_cents-a-rails-plugin/
One of the big problems with a database-agnostic framework like ActiveRecord is that it doesnâ€™t have a decent data type for money. Yes, you can use a FLOAT, but then you end up charging someone $12.3000000000000001, which is just awkward. This plugin stores as INT, but displays as Currency.