Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I access data from a joined table in my index.html.erb?
    primarykey
    data
    text
    <p>I have a Rails 4 app with two models Campus and Stat. Campus has_many stats and Stat belongs_to Campus. </p> <p>The problem I have is I can the data from my Campus table in my show action, but not in my index action. Here's the relevant code from the controllers.</p> <pre><code> def index @stats = Stat.all end def show end </code></pre> <p>Here's my show.html.erb:</p> <pre><code>&lt;p id="notice"&gt;&lt;%= notice %&gt;&lt;/p&gt; &lt;p&gt; &lt;strong&gt;Attendance:&lt;/strong&gt; &lt;%= @stat.attendance %&gt; &lt;/p&gt; &lt;p&gt; &lt;strong&gt;Salvations:&lt;/strong&gt; &lt;%= @stat.salvations %&gt; &lt;/p&gt; &lt;p&gt; &lt;strong&gt;Visitors:&lt;/strong&gt; &lt;%= @stat.visitors %&gt; &lt;/p&gt; &lt;p&gt; &lt;strong&gt;Offering:&lt;/strong&gt; &lt;%= @stat.offering %&gt; &lt;/p&gt; &lt;p&gt; &lt;strong&gt;Campus:&lt;/strong&gt; &lt;%= @stat.campus.name %&gt; &lt;/p&gt; &lt;p&gt; &lt;strong&gt;Date:&lt;/strong&gt; &lt;%= @stat.date %&gt; &lt;/p&gt; &lt;%= link_to 'Edit', edit_stat_path(@stat) %&gt; | &lt;%= link_to 'Back', stats_path %&gt; </code></pre> <p>It's outputs the following:</p> <p>Attendance: 23</p> <p>Salvations: 0</p> <p>Visitors: 3</p> <p>Offering: 5000.0</p> <p>Campus: Revelstoke</p> <p>Date: 2013-07-05</p> <p>Edit | Back</p> <p>Here's the relevant portion of my index.html.erb:</p> <pre><code>&lt;% @stats.each do |stat| %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= stat.attendance %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= stat.salvations %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= stat.visitors %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= stat.offering %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= stat.date %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= stat.time %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= stat.campus.name %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= link_to 'Show', stat %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= link_to 'Edit', edit_stat_path(stat) %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= link_to 'Destroy', stat, method: :delete, data: { confirm: 'Are you sure?' } %&gt;&lt;/td&gt; &lt;/tr&gt; &lt;% end %&gt; </code></pre> <p>The output gives me a undefined method `name' for nil:NilClass for the stat.campus.name</p> <p>I can't figure out why the difference. What am I doing wrong?</p>
    singulars
    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.
 

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