2016-03-26 9 views
1

私は以下の構造を持つ3つのモデルを持っています:参照テーブルから値を取得する方法

アプリケーションと写真belongs_toリスト。リストには写真とアプリケーションがあります。

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 

私は、ユーザーアプリケーションに関連付けられたリスティングの写真を取得しようとしています。

私は、現在のユーザーのすべてのアプリケーションを渡すことにより、コントローラで起動します。私はこのようなすべての写真を表示するビューで

@apps = current_user.applications 

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

しかし、私はこれを取得ビューをレンダリングしようとするとエラーが発生します。

未定義のメソッド `photos for nil:NilClass

この構文でアプリケーションに属するリスティングに属する写真にアクセスできません - app.listing.photos [0] .image.url?

答えて

1

あなたのアプリケーションの一部がリスティングに関連付けられていない可能性はありますか?そうである場合:

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

これを指摘していただきありがとうございます!私は関連性のないデータベースに古いレコードがたくさんあることを忘れていました。 – cremboeye

関連する問題