cremboeye
cremboeye

Reputation: 27

How to get values from referenced table Rails

I have 3 models with the following structure:

Application and Photo belongs_to Listing. Listing has_many photos and applications.

    class Listing < ActiveRecord::Base
      belongs_to :user
      has_many :photos
      has_many :applications
    end

    class Application < ActiveRecord::Base
      belongs_to :user
      belongs_to :listing
    end

    class Photo < ActiveRecord::Base
       belongs_to :listing
    end

I'm trying to get the photos of the listings that are associated with a users applications.

I start in the controller by passing all the applications of the current user:

    @apps = current_user.applications

In the view I want to display all the photos like this:

     <% @apps.each do |app| %>
        <%= image_tag app.listing.photos[0].image.url(:thumb) if app.listing.photos.length > 0 %>
     <% end %>

But I get this error when trying to render the view:

undefined method `photos' for nil:NilClass

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 ?

Upvotes: 1

Views: 260

Answers (1)

laertiades
laertiades

Reputation: 2012

Is it possible that some of your applications are not associated with any listing? If so:

<% @apps.each do |app| %>
        <%= image_tag app.listing.photos[0].image.url(:thumb) if app.listing.try(:photos).present? %>
     <% end %>

Upvotes: 1

Related Questions