简体   繁体   中英

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?

The option you need is selected , ie:

<%= 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) %>

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, eg, @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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM