Rails - 在索引视图中显示关联数据

时间:2012-12-27 17:05:19

标签: ruby-on-rails ruby ruby-on-rails-3

我努力让belongs_to模型在索引页的部分内部正确迭代。

类:

class Chapter < ActiveRecord::Base
  attr_accessible :name, :chapter_num,
  belongs_to :chapter
  #fields: :id, :name, :chapter_num
end

class County < ActiveRecord::Base
  attr_accessible :name, :county_num, :chapter_id
  has_many :counties
  #fields: :id, :name, :county_num, :chapter_id
end

class ChaptersController < ApplicationController
  def index
    @chapters = Chapter.all
    @counties = County.all(:joins => :chapter, :select => "counties.*, chapters.id")
  end
end

应用/视图/章节/ index.html.erb:

<h1>Chapter Index</h1>
  <%= render @chapters %>
<br />
<%= link_to "Add a new Chapter", new_chapter_path, class: "btn btn-large btn-primary" %>

应用/视图/章节/ _chapter.html.erb:

<div class="row">
  <div class="span5 offset1"><h4><%= link_to chapter.name, edit_chapter_path(chapter.id) %></h4></div>
  <div class="span2"><h4><%= chapter.chapter_num %></h4></div>
</div>
<!-- here's where the problem starts -->
<% @counties.each do |county| %>
<div class="row">
  <div class="span4 offset1"><%= county.name %></div>
  <div class="span4 offset1"><%= county.county_num %></div>
  <div class="span2"><%= link_to 'edit', '#' %></div>
</div>
<% end %>
<%= link_to "New county", new_county_path %>
<hr>

当前代码显示了下面的屏幕截图。问题在于它遍历所有县,而不仅仅是与给定章节相关的县。 Screenshot of Index view

如何在部分中添加章节特定变量,这将导致县根据:chapter_id字段进行迭代,因为我在索引视图中而不是显示视图?

2 个答案:

答案 0 :(得分:3)

class ChaptersController < ApplicationController
  def index
    @chapters = Chapter.all
    # @counties = County.all(:joins => :chapter, :select => "counties.*, chapters.id")
  end
end

查看:

<% chapter.counties.each do |county| %>

答案 1 :(得分:1)

我认为这样的事情会对你有用:

<%= @chapters.each do |chapter| %>

    <div class="row">
      <div class="span5 offset1"><h4><%= link_to chapter.name, edit_chapter_path(chapter.id) %></h4></div>
      <div class="span2"><h4><%= chapter.chapter_num %></h4></div>
    </div

    <% chapter.counties.each do |county| %>
        <div class="row">
          <div class="span4 offset1"><%= county.name %></div>
          <div class="span4 offset1"><%= county.county_num %></div>
          <div class="span2"><%= link_to 'edit', '#' %></div>
        </div>
    <% end %>
    <%= link_to "New county", new_chapter_county_path(chapter) %>
<% end %>

请注意,关键是要理解,因为每个章节都有很多县,所以你应该通过chapter.counties.each遍历每章的县,这只会给你属于那个特定章节的县。

另请注意创建新县的不同link_to路径。如果您设置了路线以使县嵌套在章节下,您应该能够new_chapter_county_path(chapter)