Topic: [ANSWERED] options_from_collection_for_select & array of Date objects

Hi,

I've got an array of Date objects and I'd like to create a bunch of option elements for select. How can I use strftime method to format the date the way I need? I tried:

options_from_collection_for_select(@dates, strftime("%Y"), strftime("%Y"))
options_from_collection_for_select(@dates, 'strftime("%Y")', 'strftime("%Y")')
options_from_collection_for_select(@dates, "strftime('%Y')", "strftime('%Y')")

but I get no method error.

Last edited by g0nzo (2007-07-17 14:33:58)

Re: [ANSWERED] options_from_collection_for_select & array of Date objects

Hi again,

You don't really need to bother wiht using options_from_collection_for_select (thats more from ActiveRecord objects). Instead try just using collect:

<%= select :post, :date, @dates.collect {|d| d.strftime("%Y")} %>

Alex

Re: [ANSWERED] options_from_collection_for_select & array of Date objects

Thanks! I didn't think of that smile

Just one more question - currenly I've got the following code in my controller for my @dates array:

@dates = @assignments.empty? ? [] : @assignments.collect { |assignment| assignment.assigned_for }
@dates.uniq!.sort!.collect! {|date| date.strftime("%D")} unless @dates.empty?
@dates.insert(0, "")

Is it good idea to have such code in the controller? Or should I move it somewhere?

Re: [ANSWERED] options_from_collection_for_select & array of Date objects

Normally I'd suggest moving it to the Assignments model, but as its an array, its a little more tricky, and probably not worth it. But if I understand what you're doing, your can probably be simplified quite a bit:

@dates = [""] + @assignments.to_a.collect {|a| a.assigned_for.strftime("%D")}.uniq.sort

Just a quick explanation of two parts of the code may be confusing. First the [""]  + adds on the blank value (replacing the @dates.insert(0, "") bit), and the to_a will leaves arrays unaffected, but will turn nils into a blank array. This is a neat workaround to the empty? checks you were doing.

Alex

Last edited by alexpt (2007-07-16 16:57:46)

Re: [ANSWERED] options_from_collection_for_select & array of Date objects

Thanks! Nice trick with to_a smile