Reputation: 3938
I have a collection_select dropdown that has a dropdown of names like this:
<%= f.collection_select(:person_id, Person.all, :id, :name) %>
But I have a foreign key on a person that points to a group they are part of. In the dropdown I want to show the persons name and the group next to them like this:
Paul (Golfers) Kevin (Sailors)
etc ...
Is this possible using the collection_select?
Upvotes: 3
Views: 2095
Reputation: 3938
This is actually pretty simple to do. You just need to write a method on the model you're pulling from that formats the string that you want in the dropdown. So, from the documentation:
class Post < ActiveRecord::Base
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :posts
def name_with_initial
"#{first_name.first}. #{last_name}"
end
end
Then, in your collection_select
just call that method instead of calling the name, or whatever you had show up before.
collection_select(:post, :author_id, Author.all, :id, :name_with_initial)
Seems pretty obvious in hindsight.
Upvotes: 7
Reputation: 4561
Have you tried:
<%= f.collection_select(:person_id, Person.all.collect { |p| ["#{p.name}(#{p.group})", p.id ] } ) %>
Upvotes: 0