Are we asking an interface question here (i.e. you want a widget) or an ActiveRecord question?
Date Picking Widgets
1) Default Rails Solution: See date_select
documentation here.
2) Use a plugin : Why write code? I personally like the CalendarDateSelect plugin, using a pair of the suckers when I need a range.
3) Adapt a Javascript widget to Rails: It is almost trivial to integrate something like the Yahoo UI library (YUI) Calendar, which is all Javascript, to Rails. From the perspective of Rails its just another way to populate the params[:start_date]
and params[:end_date]
. YUI Calendar has native support for ranges.
Getting the data from the Widgets
1) Default Rails Solution See date_select
documentation here.
#an application helper method you'll find helpful
#credit to http://blog.zerosum.org/2007/5/9/deconstructing-date_select
# 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
#goes into view
<%= date_select "report", "start_date", ... %>
<%= date_select "report", "end_date", ... %>
#goes into controller -- add your own error handling/defaults, please!
report_start_date = build_date_from_params("start_date", params[:report])
report_end_date = build_date_from_params("end_date", params[:report])
2) CalendarDateSelect: Rather similar to the above, just with sexier visible UI.
3) Adapt a Javascript widget: Typically this means that some form element will have the date input as a string. Great news for you, since Date.parse is some serious magic. The params[:some_form_element_name] will be initialized by Rails for you.
#goes in controller. Please handle errors yourself -- Javascript != trusted input.
report_start_date = Date.parse(params[:report_start_date])
Writing the call to ActiveRecord
Easy as pie.
#initialize start_date and end_date up here, by pulling from params probably
@models = SomeModel.find(:all, :conditions => ['date >= ? and date <= ?',
start_date, end_date])
#do something with models