Ruby on Rails collection_select显示属性

时间:2009-12-20 16:38:45

标签: ruby-on-rails

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

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

first_namelast_name

到目前为止,我只能显示其中一个,而不是两个。

这是我正在使用的代码:

collection_select(:hour,:shopper_id,@shoppers,:id,"last_name")

谢谢。

1 个答案:

答案 0 :(得分:25)

full_name方法添加到shopper模型:

class Shopper < ActiveRecord::Base
  #.....
  # add this
  def full_name
    "#{first_name} #{last_name}"
  end
end

修改collection_select声明:

collection_select(:hour,:shopper_id,@shoppers,:id,:full_name)

这是因为大多数Rails助手都将方法名称作为参数,collection_select也是如此,它采用text_method参数,这是要调用的方法的名称,用于生成文本选项本身,因此我们定义full_name方法,并将其名称传递给collection_select