Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default date and include_blank in date_select in Rails

I'm using date_select in Rails 4 and I'd like to be able to have today's date as default but also allow for the user to leave the date field blank.

<%= f.date_select(:birthdate, {include_blank: true, default: Date.today.to_date, start_year: Date.today.year - 100, end_year: Date.today.year - 18}) %>

What is the best way to allow for blank as well as have today's date appear by default when the page opens?

like image 793
jmvbxx Avatar asked Sep 17 '15 22:09

jmvbxx


Video Answer


2 Answers

The option you need is selected, i.e:

<%= f.date_select(:birthdate,
                  include_blank: true,
                  selected: Date.today, # substitute 18.years.ago to prefill year
                  start_year: Date.today.year - 100,
                  end_year: Date.today.year - 18) %>
like image 144
ahmacleod Avatar answered Oct 04 '22 14:10

ahmacleod


The approved answer will overwrite the value already assigned to the birthdate every time you go to edit the record. See here.

If your model is, e.g., @student, and your form is form_for @student do |f|, this should work. It fails through to Date.current if @student.birthdate is empty.

<%= f.date_select(:birthdate,
                  include_blank: true,
                  selected: @student.birthdate || Date.current, # Date.current respects time_zones 
                  start_year: Date.today.year - 100,
                  end_year: Date.today.year - 18) %>

However, be aware that the blank option will always be set to the current date when you go to edit the record, requiring the user to reset to blank if the data is unknown. This risks the insertion of bad data - arguably, less usable than having to choose the date to begin with.

like image 26
Jemima Avatar answered Oct 04 '22 13:10

Jemima