我正在努力让 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
app/views/chapters/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" %>
app/views/chapters/_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>
当前代码显示如下截图。问题是它遍历所有县,而不仅仅是与给定章节关联的县。
我在索引 View 中,而不是在显示 View 中,如何在局部中添加章节特定变量,这将导致县根据 :chapter_id
字段进行迭代?
最佳答案
class ChaptersController < ApplicationController
def index
@chapters = Chapter.all
# @counties = County.all(:joins => :chapter, :select => "counties.*, chapters.id")
end
end
查看:
<% chapter.counties.each do |county| %>
关于ruby-on-rails - Rails - 在索引 View 中显示相关数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14058364/