3

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?

Arel
  • 3,888
  • 6
  • 37
  • 91

2 Answers2

7

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.

Arel
  • 3,888
  • 6
  • 37
  • 91
  • Is there any way to have the dropdown populate with the current author associated with the post? I've tried :selected with no success. – Megan Woodruff May 26 '16 at 12:36
  • If you are using the form_for form builder, it should automatically populate with the value already in the database when on the update/edit view. You'll want to use form_for :post { |f| f.collection_select ... } – Arel May 26 '16 at 13:57
  • I think it is really good practice to use. It just makes helper useless – Bagi Sep 13 '17 at 07:56
0

Have you tried:

<%= f.collection_select(:person_id, Person.all.collect { |p| ["#{p.name}(#{p.group})", p.id ] } ) %>
bkunzi01
  • 4,504
  • 1
  • 18
  • 25
  • Yeah, just tried it. Getting error: wrong number of arguments (given 2, expected 4..6) – Arel May 23 '16 at 15:17