Search code examples
ruby-on-railsrubygrouped-collection-select

Collection_Select display multiple fields in dropdown


I'm using collection_select which connects to my Airports model.

Claim

belongs_to  :departure_airport, :class_name => 'Airport', :foreign_key => 'd_airport_id'
belongs_to  :arrival_airport,   :class_name => 'Airport', :foreign_key => 'a_airport_id'

Airport

has_many :claims

_form.html.erb

<%= collection_select :claim, :d_airport_id, Airport.order('name'), :id, :name, {:prompt => true} %>

Currently the dropdown displays "Manchester International Airport" (For example) however i would like to include other field names from the same model.

MAN | Manchester International Airport | EGCC (Desired result)

MAN & EGCC are both columns in the Airport model named iata & icao respectfully.


I will continue to only save the airport_id however for display purposes that additional information in the dropdown would be great.


Solution

  • You could add a method to your Airport model with the formatted string that you would like display. Something like:

    def formatted_name
      "#{iata} | #{name} | #{icao}"
    end
    

    And then pass that method to collection_select instead of :name. So:

    <%= collection_select :claim, :d_airport_id, Airport.order('name'), :id, :formatted_name, {:prompt => true} %>
    


    See the documentation here. The argument in question is referred to as the :text_method.