如何获取options_from_collection_for_select的多个字段

cir*_*le1 11 ruby-on-rails

我在select_tag中有以下内容.它工作正常.(我正在使用select_tag,因为它是针对与模型无关的搜索.)

options_from_collection_for_select(@customers, :id, :first_name)
Run Code Online (Sandbox Code Playgroud)

当前的HTML输出是:

<option value="4">Fred</option>
Run Code Online (Sandbox Code Playgroud)

但我想要:

<option value="4">Fred Flintstone</option>
Run Code Online (Sandbox Code Playgroud)

我想显示全名而不是名字.我似乎无法使用"first_name"和"last_name"这两个字段,也无法弄清楚如何调用我连接两个字段的方法.我怎样才能让它发挥作用?

Rai*_*Guy 18

在模型中添加方法full_name:

def full_name
   "#{first_name} #{last_name}"
end
Run Code Online (Sandbox Code Playgroud)

并使用这个:

options_from_collection_for_select(@customers, :id, :full_name)
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助.


Ber*_*des 13

您可以在模型上定义:

def name; "#{first_name} #{last_name}";end

并使用:

options_from_collection_for_select(@customers, :id, :name)