title: How to get values from referenced table Rails
body: <p>I have 3 models with the following structure: </p>
  
  <p>Application and Photo belongs_to Listing. Listing has_many photos and applications.  </p>
  
  <pre><code>    class Listing &lt; ActiveRecord::Base
        belongs_to :user
        has_many :photos
        has_many :applications
      end
  
      class Application &lt; ActiveRecord::Base
        belongs_to :user
        belongs_to :listing
      end
  
      class Photo &lt; ActiveRecord::Base
         belongs_to :listing
      end
  </code></pre>
  
  <p>I'm trying to get the photos of the listings that are associated with a users applications. </p>
  
  <p>I start in the controller by passing all the applications of the current user:</p>
  
  <pre><code>    @apps = current_user.applications
  </code></pre>
  
  <p>In the view I want to display all the photos like this:</p>
  
  <pre><code>     &lt;% @apps.each do |app| %&gt;
          &lt;%= image_tag app.listing.photos[0].image.url(:thumb) if app.listing.photos.length &gt; 0 %&gt;
       &lt;% end %&gt;
  </code></pre>
  
  <p>But I get this error when trying to render the view:</p>
  
  <blockquote>
    <p>undefined method `photos' for nil:NilClass</p>
  </blockquote>
  
  <p>Can't I access the photo that belongs to the listing that belongs to the application with this syntax - app.listing.photos[0].image.url ?</p>