rails 4-连接collection_select中的字段 [英] rails 4 -- concatenate fields in collection_select
问题描述
我正在通过一些教程来学习Rails 4,并构建一个演示应用程序.
I'm working on learning Rails 4 via several tutorials, and building a demo app.
我有一个名为players
的表,该表链接到team
表.球队有很多球员,一个球员只有一个球队.因此,我正在使用collection_select
标记将球队数据提取到球员表格中.
I have a table called players
that links to a team
table. The team has many players, a player has only one team. So I'm using a collection_select
tag to pull the team data into the player form.
它看起来像这样:
<%= collection_select :player, :team_id, Team.find(:all), :id, :name, options ={:prompt => "Select a team"} %>
这很好用-但我想让格式看起来像团队名称:Team City"-我不知道如何在标签中连接:name
和:city
值.这可能吗?
This works fine-- but I'd like to have the format look like "Team Name: Team City"-- I can't figure out how to concatenate the :name
and :city
values in the tag however. Is this possible?
推荐答案
在您的Team
模型中创建一个方法,如下所示:
Create a method in your Team
model like the following one
def name_with_city
"#{name}: #{city}"
end
然后按如下所示使用它
<%= collection_select :player, :team_id, Team.find(:all), :id, :name_with_city, {:prompt => "Select a team"} %>
在文档中找到有关collection_select
的更多信息
Find out more about collection_select
in the documentation
这篇关于rails 4-连接collection_select中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!