Date_select - looking for elegant solution


#1

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:

Wednesday 07 December Tuesday 06 December Monday 05 December Sunday 04 December Saturday 03 December Friday 02 December

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:

Wednesday 07 December Tuesday 06 December Monday 05 December Sunday 04 December Saturday 03 December Friday 02 December

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