我有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>
我希望:name
和:number
作为选项标记的文字:
<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>
答案 0 :(得分:1)
所以创建方法并使用它来代替名称
collection_select(:building, :room_id, Room.all, :id, :name_with_number, prompt: true)
其中name_with_number是您的方法,如
class Room < ActiveRecord::Base
def name_with_number
"#{name} #{id}" #or whatever
end
end
更多详情http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select
答案 1 :(得分:1)
在room.rb
模型中,添加一个方法来连接两个字段。
def name_with_number
name << " - " << number
end
然后将您的collection_select
更新为:
collection_select(:building, :room_id, Room.all, :id, :name_with_number, prompt: true)
祝你好运!