6
votes

Very simple question, but can't seem to work it out!! I'm creating a date of birth form, to ensure that a user can only sign up if they are over 18. I've got a date_select, and am fine setting the start year, but how do I set the end year so that it is 18 years ago? I'm going to use validators in the model as well, but don't want someone to be able to enter the wrong info in the first place.

I've looked all over, but can only find info on how to use time.ago with validators, which I've already sorted, not in the form itself.

Or, alternatively, which might be better - is there a way of having a date_select dropdown for the first two items (day & month), and a text-box for the year? Something along these lines:

<%= f.date_select :date_of_birth, :order => [:day, :month] %><%= f.text_field :date_of_birth.year, :length => 4 %>

This is what I have so far:

<%= f.label :date_of_birth %><br />
<%= f.date_select :date_of_birth, :order => [:day, :month, :year], :start_year => 1900, :end_year =>  %>

Thanks!!

3

3 Answers

3
votes

Try

Time.now.year - 18

or

Date.today.year - 18
3
votes

Found the answer on this page. Just changed it to -18 instead of +5:

<%= f.date_select :date_of_birth, :order => [:day, :month, :year], :start_year => 1900, :end_year => Time.now.year - 18 %>
2
votes

You can also do:

18.years.ago.year