Note that there are some explanatory texts on larger screens.

plurals
  1. PORails - Show associated data on Index view
    primarykey
    data
    text
    <p>I'm struggling to have a belongs_to model iterate correctly inside a partial in an index page.</p> <p><strong>Classes:</strong></p> <pre><code>class Chapter &lt; ActiveRecord::Base attr_accessible :name, :chapter_num, belongs_to :chapter #fields: :id, :name, :chapter_num end class County &lt; ActiveRecord::Base attr_accessible :name, :county_num, :chapter_id has_many :counties #fields: :id, :name, :county_num, :chapter_id end class ChaptersController &lt; ApplicationController def index @chapters = Chapter.all @counties = County.all(:joins =&gt; :chapter, :select =&gt; "counties.*, chapters.id") end end </code></pre> <p><strong>app/views/chapters/index.html.erb:</strong></p> <pre><code>&lt;h1&gt;Chapter Index&lt;/h1&gt; &lt;%= render @chapters %&gt; &lt;br /&gt; &lt;%= link_to "Add a new Chapter", new_chapter_path, class: "btn btn-large btn-primary" %&gt; </code></pre> <p><strong>app/views/chapters/_chapter.html.erb:</strong></p> <pre><code>&lt;div class="row"&gt; &lt;div class="span5 offset1"&gt;&lt;h4&gt;&lt;%= link_to chapter.name, edit_chapter_path(chapter.id) %&gt;&lt;/h4&gt;&lt;/div&gt; &lt;div class="span2"&gt;&lt;h4&gt;&lt;%= chapter.chapter_num %&gt;&lt;/h4&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- here's where the problem starts --&gt; &lt;% @counties.each do |county| %&gt; &lt;div class="row"&gt; &lt;div class="span4 offset1"&gt;&lt;%= county.name %&gt;&lt;/div&gt; &lt;div class="span4 offset1"&gt;&lt;%= county.county_num %&gt;&lt;/div&gt; &lt;div class="span2"&gt;&lt;%= link_to 'edit', '#' %&gt;&lt;/div&gt; &lt;/div&gt; &lt;% end %&gt; &lt;%= link_to "New county", new_county_path %&gt; &lt;hr&gt; </code></pre> <p>The current code shows the screenshot below. The problem is it's iterating through all the counties, not just the counties associated with a given chapter. <img src="https://i.stack.imgur.com/pnmxA.jpg" alt="Screenshot of Index view"></p> <p>How do I add a chapter specific variable within the partial that will cause the counties to iterate based upon the <code>:chapter_id</code> field since I'm in the index view, not the show view?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload