我正在努力让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
字段进行迭代,因为我在索引视图中,而不是显示视图?