camillavk
camillavk

Reputation: 521

Display collection_select dropdown with dates in words

I'm trying to create a simple dropdown with collection_select for some dates, but I am struggling to display the dates in words as times from now (i.e. "One month from today")

So far I have:

def dates_for_review_select
    [Date.today, (Date.today + 2.weeks), (Date.today + 1.month), (Date.today + 2.months), (Date.today + 3.months)]
end

and

<%= f.collection_select :uk_review_at, dates_for_review_select, :to_s, :to_s, {}, :class => "form-control" %>

(from here -> RoR - collection_select from array)

But I don't know how to change how the dates are displayed. At the moment it is displaying them as normal dates, but I want them to display using the rails "distance_of_time_in_words" helper, so it says how far away the date is in words.

But I don't know how or where to implement this? Any ideas?

Upvotes: 3

Views: 426

Answers (2)

SteveTurczyn
SteveTurczyn

Reputation: 36860

options_for_select will take an array of arrays, the first element of each sub array is the display value, the second element is the value returned.

So this should work...

def dates_for_review_select
    [Date.today, (Date.today + 2.weeks), (Date.today + 1.month), (Date.today + 2.months), (Date.today + 3.months)]
end

<%= f.select :uk_review_at, options_for_select(dates_for_review_select.map{|d| [distance_of_time_in_words(Date.today, d), d]}), {}, :class => "form-control review-date" %>

Edited to use the final version that camillavk used.

Upvotes: 3

ahmacleod
ahmacleod

Reputation: 4310

You can improve readability by passing dates_for_review_select as the collection object, :itself as the value function, and a lambda using distance_of_time_in_words for the text function.

<%= f.collection_select(
      :uk_review_at,
      dates_for_review_select,
      :itself,
      -> (t) { distance_of_time_in_words(Date.today, t) },
      class: 'form-control review-date') %>

Upvotes: 0

Related Questions