Ruby on Rails collection_select显示属性

New*_*ils 11 ruby-on-rails

我是Rails的新手,正在使用该collection_select方法.

我有两个要在选择框中显示的字段:

first_namelast_name

到目前为止,我只能显示一个或另一个,而不是两者.

这是我正在使用的代码:

collection_select(:hour,:shopper_id,@shoppers,:id,"last_name")
Run Code Online (Sandbox Code Playgroud)

谢谢.

khe*_*lll 25

添加full_name方法到shopper模型:

class Shopper < ActiveRecord::Base
  #.....
  # add this
  def full_name
    "#{first_name} #{last_name}"
  end
end
Run Code Online (Sandbox Code Playgroud)

并修改collection_select声明:

collection_select(:hour,:shopper_id,@shoppers,:id,:full_name)
Run Code Online (Sandbox Code Playgroud)

这是因为大多数Rails助手都将方法名称作为params,collection_select也是如此,它接受一个text_methodparam,这是要调用的方法的名称,用于生成选项本身的文本,因此我们定义full_name方法并传递它的名称到collection_select.