If this has been answered before I cannot find it.
如果在我找不到它之前已经回答了这个问题。
I have the following:
我有以下内容:
= f.collection_select :sex_id, @sexes, :id, :name
and this in the controller:
这在控制器中:
@sexes = Sex.all
the sexes are all stored in lowercase, like this:
性别都以小写形式存储,如下所示:
id|name
1|steer
2|heifer
3|holstein
I need them to output with Capital First letters:
我需要他们用Capital First字母输出:
Steer
Heifer
Holstein
I tried:
= f.collection_select :sex_id, @sexes, :id, :name.capitalize
= f.collection_select :sex_id, @sexes, 'id', 'name'.capitalize
but they do not work, and I didn't really expect them to, but had to try them before posting this.
但它们不起作用,我并没有真正期待它们,但在发布之前不得不尝试它们。
3 个解决方案
#1
6
collection_select
calls a method on each object to get the text for the option value. You can add a new method in the model to get the right value:
collection_select在每个对象上调用一个方法来获取选项值的文本。您可以在模型中添加新方法以获得正确的值:
def name_for_select
name.capitalize
end
then in the view:
然后在视图中:
= f.collection_select :sex_id, @sexes, :id, :name_for_select
#2
0
The reason your initial attempt is not working is that you're attempting to capitalize a symbol or a string that represents the field name and not the actual variable.
您的初始尝试不起作用的原因是您试图将表示字段名称的符号或字符串大写,而不是实际变量。
You could do something like this and then the data would be capitalized before it's sent to the view.
您可以执行类似的操作,然后在将数据发送到视图之前将数据大写。
@sexes = Sex.all
@sexes = @sexes.each{|sex| sex.name.capitalize}
or
@sexes = Sex.all.each{|sex| sex.name.capitalize}
#3
0
The simpler way to do this in RoR4 would be to use the humanize method. So, your view code would look like this:
在RoR4中执行此操作的更简单方法是使用humanize方法。因此,您的视图代码如下所示:
= f.collection_select :sex_id, @sexes, :id, :humanize
No need for any extra methods!
不需要任何额外的方法!
#1
6
collection_select
calls a method on each object to get the text for the option value. You can add a new method in the model to get the right value:
collection_select在每个对象上调用一个方法来获取选项值的文本。您可以在模型中添加新方法以获得正确的值:
def name_for_select
name.capitalize
end
then in the view:
然后在视图中:
= f.collection_select :sex_id, @sexes, :id, :name_for_select
#2
0
The reason your initial attempt is not working is that you're attempting to capitalize a symbol or a string that represents the field name and not the actual variable.
您的初始尝试不起作用的原因是您试图将表示字段名称的符号或字符串大写,而不是实际变量。
You could do something like this and then the data would be capitalized before it's sent to the view.
您可以执行类似的操作,然后在将数据发送到视图之前将数据大写。
@sexes = Sex.all
@sexes = @sexes.each{|sex| sex.name.capitalize}
or
@sexes = Sex.all.each{|sex| sex.name.capitalize}
#3
0
The simpler way to do this in RoR4 would be to use the humanize method. So, your view code would look like this:
在RoR4中执行此操作的更简单方法是使用humanize方法。因此,您的视图代码如下所示:
= f.collection_select :sex_id, @sexes, :id, :humanize
No need for any extra methods!
不需要任何额外的方法!