2

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.

Pholochtairze
  • 1,836
  • 1
  • 14
  • 18
Dearg
  • 47
  • 10

2 Answers2

4

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.

mlovic
  • 864
  • 6
  • 11
0

The following should help you : rails 4 -- concatenate fields in collection_select

Basically, you create in your Airport model a new method (in models/Airport.rb):

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

And in _form.html.erb you use the newly created collection_select_nice_data:

<%= collection_select :claim, :d_airport_id, Airport.order('name'), :id, :collection_select_nice_data, {:prompt => true} %>
Community
  • 1
  • 1
Pholochtairze
  • 1,836
  • 1
  • 14
  • 18
  • thank you for your answer and link too. Both answers seem to be pretty identical so i chose the first provided as the accepted answer. Thanks again. – Dearg Jun 03 '16 at 11:29