Rails - 从循环的每次迭代的表中获取数据
抱歉这个新手问题,但我不知道如何做到这一点..
我有以下城市表
# Table name: cities
#
# id :integer
# name :string(255)
# country :string(255)
(注意:我没有使用单独的国家/地区表,因为我使用 Geokit-rails 并认为将所有 Google 查询存储在但是,使用单独的表来通过“belong_to/has_many”关联来呈现我想要的内容会更容易)
在我的城市/索引视图中,我想循环每个国家/地区的所有城市,以便呈现类似以下内容的内容
United States
New York
San Francisco
Los Angeles
United Kingdom
London
Spain
Madrid
...
: ,我能得到的就是它 提供
由脚手架模型
def index
@cities = City.all
end
视图
<table>
<% for city in @cities %>
<tr>
<th><%= city.country %></th>
</tr>
<tr>
<td><%= city.name %></td>
</tr>
<% end %>
</table>
渲染
United States
Los Angeles
United States
New York
...
:我没有找到任何关于此的资源。如果有人可以帮助我,我会很高兴(我不知道我必须从哪一个开始:find_by_ /params /each 或 collection?)
非常感谢!
Sorry for this newbie question but I cannot figure how I can do this..
I have the following City table
# Table name: cities
#
# id :integer
# name :string(255)
# country :string(255)
(note: I am not using a separate Country table as I use Geokit-rails and think it is simpler to store all Google queries in the same table. However It would be easier to have separate tables to render what I want through a belong_to/has_many association)
In my city/index view I want to loop all the cities for each countries in order to render something like:
United States
New York
San Francisco
Los Angeles
United Kingdom
London
Spain
Madrid
...
By now, What I can get is what it provided by scaffolding
Model
def index
@cities = City.all
end
View
<table>
<% for city in @cities %>
<tr>
<th><%= city.country %></th>
</tr>
<tr>
<td><%= city.name %></td>
</tr>
<% end %>
</table>
Rendering:
United States
Los Angeles
United States
New York
...
I didn't find any resource about this. I would be pleased if someone could help me (I don't know with which I have to start: find_by_ /params /each or collection?)
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正确的方法是使用
id
和name
创建一个Country
表,并在您的City
模型中创建将country_id
保留为国家/地区,而不是字符串,以便
您可以调用
Country.includes(:cities)
并在您的视图中像这样迭代它们:如果您仍然想用你的方式,你可以做类似的事情
The correct way to do this is to create a
Country
table withid
andname
and in yourCity
model just keep acountry_id
to the country, instead of a stringso
then you can call
Country.includes(:cities)
and iterate over them like this in your view:If you still want to use your way, you could do something like
我已经成功使用
group_by
方法:输出:
当然,您可能会在 erb 模板中执行此操作,但想法是相同的:
输出:
I've had success with the
group_by
method:Output:
Of course, you'll probably be doing this in an erb template, but the idea is the same:
Output:
官方 rails 指南 是一个很好的起点 ;)
The official rails guides are an excellent place to start ;)