ikanyu ikanyu - 4 months ago 10
Ruby Question

options_from_collection_for_select's text_method date conversion

I intend to create a dropdown for selection.

Expected Outcome:

March 2016
August 2016

With these code, as my dropdown is showing as below as database is storing the YY-MM-DD


Here's my code:

<%= form_tag('/admin/users', method: :get) do %>
<%= select_tag "intake_date", options_from_collection_for_select(Membership.select(:intake_date).distinct, 'intake_date', 'intake_date')%>
<%= submit_tag %>
<% end %>

I've tried changing the

Membership.all.pluck(:intake_date).uniq.inject{ |date| date.strftime(%B %Y) }

but the outcome is still not as expected.


Both the value and text methods for collection select can respond to a method call, which yields the instance of the object, the result would be used for select options.

In your case, you should be able to solve with:

select_tag 'intake_date', options_from_collection_for_select(Membership.pluck(:intake_date), :to_s, proc{|date| date.strftime("%B %Y")})

This is assuming you will parse the date before saving the record in your db, as the value method is a date string