zerosum dirt(nap)

evolution through a series of accidents

zerosum dirt(nap)

Deconstructing date_select

May 09, 2007 by nap · Comments

date_select and it’s friend datetime_select are handy little helpers for rendering date selection widgets in your form, but what they hand back to your controller is a little bit unintuitive. If you’re just going to go ahead and use update_attributes on your model, then ActiveRecord magically takes care of converting these to an appropriate Date or Time object for you. However, if you’re not doing that, you’ll find yourself staring at keys in your hash named odd things like “attribute(1i)”.

Here’s a handy little helper method, in case you ever need to manually reconstruct a Date object from the params:

# Reconstruct a date object from date_select helper form params
def build_date_from_params(field_name, params)
  Date.new(params["#{field_name.to_s}(1i)"].to_i, 
           params["#{field_name.to_s}(2i)"].to_i, 
           params["#{field_name.to_s}(3i)"].to_i)
end

date = build_date_from_params(:published_at, params[:article])

Put this in your ApplicationController so inherited controller classes can access it, or (better yet) put it in a suite of helper methods to mix in to application.rb. Not exactly brain surgery here, but I’m a little surprised that there isn’t something already baked into the helpers to do this.

blog comments powered by Disqus