2009-12-20 129 views
11

我是Rails的新手,正在使用collection_select方法。Ruby on Rails collection_select显示属性

我有两个领域,我想在我的选择框中显示:

first_namelast_name

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

这里是我的工作代码:

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

谢谢。

回答

24

添加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的helper需要方法名作为参数,可以这样做collection_select,这需要一个text_method帕拉姆,这是要调用的方法的名称,以生成该选项本身的文本,因此我们定义full_name方法,我们传递它的名字t o collection_select

+0

太好了,谢谢! – New2rails 2009-12-20 16:54:47