2012-07-17 113 views
0

我一直试图通过关联模型将索引中的模型分组。Rails 3 group_by关联模型

下面是我有:

我有模型location.rb

​​

属于Continent.rb

has_many :locations 

locations_controller.rb

def index 
    @locations = Location.find(:all) 
    end 

和在米y索引页

<% @locations.group_by(&:continent_id).each do |continent, locations| %> 

    <li><%= continent %></li> 
    <% locations.each do |location| %>  
    <%= location.name %> 
    <% end %> 
<% end %> 

我想按大洲分组位置。上面的代码工作,但我只需要显示大陆的名称,现在它只显示ID号。

这样做的最佳方法是什么? 我是新手,我知道这一定很容易,但我有点卡住了。

谢谢。

+1

也许你可以尝试只<%@ locations.group_by(:大陆)。每个办...... – 2012-07-17 17:25:20

+0

是的,这是它,谢谢! :)) – emilsw 2012-07-17 17:36:16

+0

也@locations = Location.all更好:) – 2012-07-18 04:51:09

回答

0

首先,在我看来,你列出了大陆,而不是地点(以保持它的安宁)。所以我会改变大陆控制器。在大陆控制器:

def index 
    @continents = Continent.find(:all) 
end 

在大陆/ index.html.erb:

<% @continents.each do |continent| %> 
    <li><%= continent.name %></li> 
    <% continent.locations.each do |location| %>  
    <%= location.name %> 
    <% end %> 
<% end %> 
+0

是的,这也有道理......谢谢! – emilsw 2012-07-17 17:49:18