This post originated from an RSS feed registered with Ruby Buzz
by Bob Silva.
Original Post: User Friendly Time Entry
Feed Title: Rails Video Tutorials
Feed URL: http://www.railtie.net/xml/rss/feed.xml
Feed Description: A growing collection of screencasts that show you how to use the many facets of the wonderful world of rails.
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
end
def get_travel_time
travel_time.to_i.divmod(60)
end
Controller Code (models_controller.rb):
def create
@model.new(...)
...
@model.set_travel_time(params[:hours], params[:minutes])
...
if @model.save
...
end
def edit
@model = Model.find(...)
...
@hours, @minutes = @model.get_travel_time
...
end