1
votes

I'm trying to set up a custom date select in rails. Rails provides a form helper for this called date_select. (<%= f.date_select %> in practice)

However the HTML that this gives is: (Showing just the month for brevity.)

<select id="event_starttime_2i" name="event[starttime(2i)]">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12" selected="selected">December</option>
</select>

I want it to be a little smarter, however. I want the user to be offered a dropdown that allows them to select dates from "today" to a "week from today" and not force them to select "year"/"month"/"day" individually. My main concern is the ability of Rails to submit custom "select" options as "datetime" attributes. (The date_select helper actually sends 3 http parameters: starttime(1i), starttime(2i) and starttime(3i). ActiveRecord must combine those into a single Date before updating the row in the database. I'm only wanting the one dropdown and this is a concern.)

This is kind of what I'm going for:

<select>
<option value="1"><%= Date.today %> </option>
<option value="2"><%= Date.today + 1%></option>
<option value="3"><%= Date.today + 2%></option>
<option value="4"><%= Date.today + 3%></option>
<option value="5"><%= Date.today + 4%></option>
<option value="6"><%= Date.today + 5%></option>
<option value="7"><%= Date.today + 6%></option>
</select>

The last code snippet won't run here. It looks like this in practice:

<select>
<option value="1">2016-12-27</option>
<option value="2">2016-12-28</option>
<option value="3">2016-12-29</option>
<option value="4">2016-12-30</option>
<option value="5">2016-12-31</option>
<option value="6">2016-01-01</option>
<option value="7">2016-01-02</option>
</select>

How do I get this to work? (Persist on submit as a datetime attribute of my model)

1

1 Answers

2
votes

If you can rely on JavaScript I suggest using bootstrap-datepicker-rails. You can find an excellent demo here. It's highly customizable and installation is straightforward.