AnthonyGalli.com AnthonyGalli.com - 3 months ago 13
Ruby Question

collection_select show multiple object attributes?

In addition to showing the challenge's

name
. I also want to show its
deadline
next to the
name
.

It would look like this for example:

Visit London 09/09/16
Make $1,000,000 10/15/18
Knit a Scarf 01/11/19


Instead of just this:

enter image description here

<%= f.collection_select :challenge_id, current_user.challenges.order(:deadline),:id,:name, include_blank: true %>

Answer

Define a method name_with_deadline in challenge.rb

def name_with_deadline
  "#{name} #{deadline}"
end

and then make use of this method as label in the collection.

<%= f.collection_select :challenge_id, current_user.challenges.order(:deadline),:id, :name_with_deadline, include_blank: true %>

The name_with_deadline method will called for every object in the collection to retrieve the label text.

Hope this helps!