开发者

Use Rails select_month and select_year to capture and store dates

开发者 https://www.devze.com 2022-12-19 23:47 出处:网络
I would like to use two picklists to control entry into a date field; I\'m concerned with the month and year, not the da开发者_开发技巧y.So far, I have the following:

I would like to use two picklists to control entry into a date field; I'm concerned with the month and year, not the da开发者_开发技巧y. So far, I have the following:

<tr>
  <td>Date Range:</td>
  <td>
    <%= select_month(Date.today, :field_name=>"dateStarted") %>
    <%= select_year(Date.today, :field_name=>"dateStarted") %>
    &nbsp;to&nbsp;
    <%= select_month(Date.today, :field_name=>"dateEnded") %>
    <%= select_year(Date.today, :field_name=>"dateEnded") %>
  </td>
</tr>

This will correctly set the month and year corresponding to today's date. Unfortunately, the select fields do not respond to values in the respective fields. What am I missing?

Moreover, I assume that I will need to combine these two fields in the controller's create and update actions to create an actual date that will be stored in the db, but I am unclear how to do so.

Help is appreciated.


Why not just use date_select (rather than select_month and select_year)

date_select("dateRange","dateStarted", {:default => Date.today, :discard_day => true})
date_select("dateRange","dateEnded", {:default => Date.today, :discard_day => true})

This will create parameters dateRange[dateStarted] and dateRange[dateEnded] with sub-selects for year and month.

One other clarification, to make it work seamlessly with the create and update action, you should replace "dateRange" with the actual model name. That way it will be properly embedded in the parameter hash


If you are using simple form in your rails application, then you can do something like:

= simple_form_for(resource) do |f|
  // ...
  = f.input :date_started, discard_day: true, end_year: Date.today.year, order: [:month, :year]
  = f.input :date_ended, discard_day: true, end_year: Date.today.year, order: [:month, :year]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号