0

関連付けられたモデルによってインデックス内のモデルをグループ化しようとしています。

これが私が持っているものです:

モデルlocation.rbがあります

  belongs_to :continent   

Continent.rbに属します

  has_many :locations

location_controller.rb

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

と私のインデックスページで

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

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

場所を大陸ごとにグループ化したい。上記のコードは機能しますが、大陸の名前を表示するだけで、idnrのみが表示されます。

それを行うための最良の方法は何ですか?私は初心者で、これは簡単なはずですが、少し行き詰まっています。

ありがとう。

4

1 に答える 1

0

まず、場所ではなく大陸をリストしているように見えます(休息を保つため)。だから私は大陸のコントローラーのためにそれを変更します。大陸コントローラーの場合:

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

continents / index.html.erbの場合:

<% @continents.each do |continent| %>
  <li><%= continent.name %></li> 
  <% continent.locations.each do |location| %>    
    <%= location.name %> 
  <% end %>
<% end %>
于 2012-07-17T17:35:57.330 に答える