How To Use date_select for Birth Date Field
The date selection date_select widget by default contains years from five years before to five years after the current date.
This is not sufficient for a birth date field.
Default Data Selection
Let’s assume that you used the scaffold generator to generate controller and views; a date field should look like:
-
<p><label for="employee_date_of_birth">Date of birth</label><br/>
-
<%= date_select ‘employee’, ‘date_of_birth’ %></p>
This date selection is not sufficient (maybe it is if your application is designed for a kindergarten ;).
Set Options
We have to set the start_year and the end_year options.
The start_year should contain a value equal to the current year and decreased by the supposed maximal age; the end_year should contain a value equal to the current year. The current year we can get by calling the following code:
Time.now.year
Solution
A date selection with a correct list of years:
-
<p><label for="employee_date_of_birth">Date of birth</label><br/>
-
<%= date_select ‘employee’, ‘date_of_birth’,
-
:start_year => Time.now.year - 100,
-
:end_year => Time.now.year %></p>
Advanced Solution
If you plan to use this on more places, of course you should reduce the amount of a copy&paste code and if there is a requirement to change the boundaries, it should be in one place.
Add the following code to the app/helpers/application_helper.rb file the following lines:
-
def getBirthDateStart()
-
Time.now.year - 100
-
end
-
-
def getBirthDateEnd()
-
Time.now.year
-
end
and change the date selection code to:
-
<p><label for="employee_date_of_birth">Date of birth</label><br/>
-
<%= date_select ‘employee’, ‘date_of_birth’,
-
:start_year => getBirthDateStart(),
-
:end_year => getBirthDateEnd() %></p>
That is it :)










