Forum: Ruby on Rails date_select - looking for elegant solution

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
jeroen (Guest)
on 2005-12-07 16:21
(Received via mailing list)
Hi,

I have a model with a date field (date column in Postgresql 8.0)
I want the form to display a list of, say 5, dates using only 1
selectbox, like this:

<option value="2005-12-07">Wednesday 07 December</option>
<option value="2005-12-06">Tuesday 06 December</option>
<option value="2005-12-05">Monday 05 December</option>
<option value="2005-12-04">Sunday 04 December</option>
<option value="2005-12-03">Saturday 03 December</option>
<option value="2005-12-02">Friday 02 December</option>

I got this working using a helper method and the select tag in the view.

Helper:

def days_ago_array
   days = []
   today = Time.new
   for i in 0..5
     day = today - i.days
     days << [day.strftime("%A %d %B"), day.strftime("%Y-%m-%d")]
   end
   days
end

View:

<%=select("match", "match_date", days_ago_array)%>

So, if I submit 05 december I would expect this:

<option value="2005-12-07">Wednesday 07 December</option>
<option value="2005-12-06">Tuesday 06 December</option>
<option value="2005-12-05" selected="selected">Monday 05
December</option>
<option value="2005-12-04">Sunday 04 December</option>
<option value="2005-12-03">Saturday 03 December</option>
<option value="2005-12-02">Friday 02 December</option>

But instead none of the options are selected, even though the match_date
attribute *is* set the 05 december. I think the selectbox probably
expects a string but instead a Date object is passed to it so it can't
work out which option to select. So I added this method to my model:

def match_date
   super.to_s
end

The date is returned as a string and now everything works as expected,
but I can no longer access by match_date as a Date object, thus I cannot
do <%=@match.match_date.strftime("%A %d %B")%> anymore.. Or can I? Is
there a smarter solution?

Jeroen
This topic is locked and can not be replied to.