1

我正在努力让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>

当前代码显示了下面的屏幕截图。问题是它会遍历所有县,而不仅仅是与给定章节相关的县。索引视图的屏幕截图

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

4

2 回答 2

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| %>
于 2012-12-27T17:37:27.383 回答
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)

于 2012-12-27T17:43:07.833 回答