ruby-on-rails - Rails - 在索引 View 中显示相关数据

标签 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

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>

当前代码显示如下截图。问题是它遍历所有县,而不仅仅是与给定章节关联的县。 Screenshot of Index view

我在索引 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/

相关文章:

ruby-on-rails - rails 复制 : remapping associations

ruby - 继承但不与父类(super class)共享,不共享命名空间的变量/常量

ruby - 在 Redis 中为 Ruby 重新创建 zdiffstore

ruby - 使用 Scripting Bridge 进行回调?

ruby-on-rails-3 - Rails 3.2.2 操作被调用两次

ruby-on-rails-3 - 当发生任何异常时,如何在引发异常的位置自动启动 Rails/Ruby 中的 Pry

ruby-on-rails - Capistrano 3须藤任务

ruby-on-rails - 我应该如何添加用户配置文件和隐私来设计?

ruby-on-rails - 带有RVM的Mac OSX上的Rails Segmentation Fault

ruby-on-rails - 如何将acts-as-taggable-on 集成到RailsAdmin?