我是Rails的新手,正在使用collection_select
方法。
我想在我的选择框中显示两个字段:
first_name
和last_name
到目前为止,我只能显示其中一个,而不是两个。
这是我正在使用的代码:
collection_select(:hour,:shopper_id,@shoppers,:id,"last_name")
谢谢。
答案 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
。