I'm new to Rails and am working with the collection_select
method.
我是Rails的新手,正在使用collection_select方法。
I have two fields I'd like to display in my select box:
我有两个要在选择框中显示的字段:
first_name
and last_name
first_name和last_name
So far, I can only display one or the other, not both.
到目前为止,我只能显示一个或另一个,而不是两者。
Here's the code I'm working with:
这是我正在使用的代码:
collection_select(:hour,:shopper_id,@shoppers,:id,"last_name")
Thank you.
谢谢。
1 个解决方案
#1
25
Add full_name
method to shopper
model:
将full_name方法添加到购物者模型:
class Shopper < ActiveRecord::Base
#.....
# add this
def full_name
"#{first_name} #{last_name}"
end
end
And modify the collection_select
statement:
并修改collection_select语句:
collection_select(:hour,:shopper_id,@shoppers,:id,:full_name)
This is because most of Rails helpers takes methods names as params, so does collection_select, which takes a text_method
param, which is the name of the method to be called to generate the text of the option itself, thus we define full_name
method and we pass it's name to collection_select
.
这是因为大多数Rails助手都将方法名称作为参数,collection_select也是如此,它采用text_method参数,这是要调用的方法的名称,用于生成选项本身的文本,因此我们定义了full_name方法,我们通过了它是collection_select的名字。
#1
25
Add full_name
method to shopper
model:
将full_name方法添加到购物者模型:
class Shopper < ActiveRecord::Base
#.....
# add this
def full_name
"#{first_name} #{last_name}"
end
end
And modify the collection_select
statement:
并修改collection_select语句:
collection_select(:hour,:shopper_id,@shoppers,:id,:full_name)
This is because most of Rails helpers takes methods names as params, so does collection_select, which takes a text_method
param, which is the name of the method to be called to generate the text of the option itself, thus we define full_name
method and we pass it's name to collection_select
.
这是因为大多数Rails助手都将方法名称作为参数,collection_select也是如此,它采用text_method参数,这是要调用的方法的名称,用于生成选项本身的文本,因此我们定义了full_name方法,我们通过了它是collection_select的名字。