AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

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 %>

Upvotes: 0

Views: 106

Answers (2)

dp7
dp7

Reputation: 6749

You can add a virtual attribute to you model like below:

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

collection_select:

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

Upvotes: 1

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

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!

Upvotes: 1

Related Questions