Bruno
Bruno

Reputation: 6449

Show concatenated text for collections_select option text

I have a collections_select:

collection_select(:building, :room_id, Room.all, :id, :name, prompt: true):

<select name="building[room_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">Room A</option>
  <option value="2">Room B</option>
  <option value="3">Room C</option>
</select>

I would like to have :name and :number as the text for the options tag:

<select name="building[room_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">Room A - 101</option>
  <option value="2">Room B - 102</option>
  <option value="3">Room C -103</option>
</select>

Upvotes: 2

Views: 26

Answers (2)

RAJ
RAJ

Reputation: 9747

In your room.rb model, add a method to concatenate two fields.

def name_with_number
  name << " - " << number
end

Then update your collection_select as:

collection_select(:building, :room_id, Room.all, :id, :name_with_number, prompt: true)

Good Luck!

Upvotes: 1

Fivell
Fivell

Reputation: 11929

so create method and use it instead name

collection_select(:building, :room_id, Room.all, :id, :name_with_number, prompt: true)

where name_with_number is your method like

class Room < ActiveRecord::Base
  def name_with_number
     "#{name} #{id}" #or whatever
   end
end

More details http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

Upvotes: 1

Related Questions