Victor Christensen
Victor Christensen

Reputation: 3

How do I expand the range of years available in dropdown menu when using the :date datatype in Rails 5?

I am writing a personal genealogy app with Ruby on Rails 5, and am using the :date datatype for entering birth/death dates. This results in a dropdown menu for each element (year/month/day) of a date. For the year, the menu defaults to a range of five years in the past to five years in the future (so for 2017, the range is from 2012 to 2022). But I need to have a much larger range to cover years going back multiple centuries. How can I define a specific range of years I want to be available in the dropdown menu?

Here's an excerpt from my schema.rb file (other fields deleted for brevity):

create_table "people", force: :cascade do |t|
  t.date "birth_date"
  t.date "death_date"
end

And here's and excerpt from my view file (again, other fields deleted for brevity):

<div class="booyah-box col-10 offset-1">

  <h1>Edit Your Person Details</h1>
  <%= simple_form_for @person do |f| %>

    <%= f.input :birth_date %>
    <%= f.input :death_date %>

    <%= f.submit 'Update', class: 'btn btn-primary' %>
  <% end %>

</div>

I should also add I need a way to have a "no choice"-type option, such as for those still living, since they wouldn't have a death date

I've searched on StackOverflow and haven't found an applicable answer, but if there's already one here, please point me to it. Thanks in advance for your help.

Upvotes: 0

Views: 208

Answers (1)

Gerry
Gerry

Reputation: 10507

You can specify the start_year and end_year in the date input within your view; for example:

<div class="booyah-box col-10 offset-1">

  <h1>Edit Your Person Details</h1>
  <%= simple_form_for @person do |f| %>

    <%= f.input :birth_date, start_year: Time.now.year - 10, end_year: Time.now.year + 10 %>
    <%= f.input :death_date, start_year: Time.now.year - 10, end_year: Time.now.year + 10, prompt: "-" %>

    <%= f.submit 'Update', class: 'btn btn-primary' %>
  <% end %>

</div>

In the example I added 10 years from current date and 10 years after current date, but you can use any range you need.

Upvotes: 1

Related Questions