在 collection_select 上使用大写

发布于 2024-10-03 18:40:58 字数 547 浏览 9 评论 0原文

如果之前已经回答过这个问题,我就找不到它了。

我有以下内容:

= f.collection_select :sex_id, @sexes, :id, :name

在控制器中:

@sexes = Sex.all

性别全部以小写形式存储,如下所示:

id|name
 1|steer
 2|heifer
 3|holstein

我需要它们以大写字母输出:

Steer
Heifer
Holstein

我尝试过:

= f.collection_select :sex_id, @sexes, :id, :name.capitalize
= f.collection_select :sex_id, @sexes, 'id', 'name'.capitalize

但它们不起作用,我真的没想到它们会,但在发布此内容之前必须尝试一下。

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:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

高跟鞋的旋律 2024-10-10 18:40:58

collection_select 在每个对象上调用一个方法来获取选项值的文本。您可以在模型中添加一个新方法来获取正确的值:

def name_for_select
  name.capitalize
end

然后在视图中:

= f.collection_select :sex_id, @sexes, :id, :name_for_select

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:

def name_for_select
  name.capitalize
end

then in the view:

= f.collection_select :sex_id, @sexes, :id, :name_for_select
甜心小果奶 2024-10-10 18:40:58

您最初的尝试不起作用的原因是您尝试将代表字段名称而不是实际变量的符号或字符串大写。

您可以执行类似的操作,然后数据在发送到视图之前将被大写。

@sexes = Sex.all    
@sexes = @sexes.each{|sex| sex.name.capitalize}

或者

@sexes = Sex.all.each{|sex| sex.name.capitalize}

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}
树深时见影 2024-10-10 18:40:58

在 RoR4 中执行此操作的更简单方法是使用 humanize< /a> 方法。因此,您的视图代码将如下所示:

= f.collection_select :sex_id, @sexes, :id, :humanize

不需要任何额外的方法!

The simpler way to do this in RoR4 would be to use the humanize method. So, your view code would look like this:

= f.collection_select :sex_id, @sexes, :id, :humanize

No need for any extra methods!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文