Search code examples
ruby-on-railscollection-select

Customizing the text in a collection_select dropdown


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?


Solution

  • 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.