2016-07-29 6 views
0

3モデルあります。下記に定義されるように彼らは、次のとおりです。1対1の関連付けを持つ3つのモデルからレコードをフェッチする方法は?

#Checkout Model 
class Checkout < ActiveRecord::Base 
    belongs_to :gallery_visitor 
end 

#GalleryVisitor Model 
class GalleryVisitor < ActiveRecord::Base 
    belongs_to :gallery 
    has_one :checkout 
end 

#Gallery Model 
class Gallery < ActiveRecord::Base 
    has_many :gallery_visitors, dependent: :destroy 
end 

私はチェックアウトのモデルに基づいて、すべてのギャラリーをフェッチするために喜んで。 includes()を使うにはどうしたらいいですか? 誰か助けてくれますか?アドバイスでありがとう。

答えて

2

ねえ、あなたがこの方法を試すことができます。

Gallery.includes({gallery_visitors: [:checkout]}).where(checkouts: {condition}) 
+0

私は彼がチェックアウトのためにギャラリーを必要と思うと思う。 –

+0

@Deepakあなたの質問はギャラリーではなくチェックアウトを返す。上記のクエリでは、チェックアウトモデルに条件を置くことができます。ギャラリを返します –

+0

@Deepak Vishalは正しいです。 –

1

あなたも以上のレールで

Gallery to Checkout through Gallery Visitors、から関連付けを追加することによって、このクエリshorterquickerを作ることができます方法。

class Gallery < ActiveRecord::Base 
    has_many :gallery_visitors, dependent: :destroy 
    has_one :checkout,through: :gallery_visitors 
end 

これは直接関係船となりますを作るコンソールをリロードし、

Gallery.includes(:checkout).where(checkout: {condition})

Eg: Gallery.includes(:checkout).where(checkout: {id: 1})

このクエリを試してみてください、ギャラリーモデルにラインhas_one :checkout,through: :gallery_visitorsを追加します。クエリはより速くなります。

関連する問題