2016-09-20 50 views
1

我正在嘗試爲基於孫子狀態的類創建範圍。Rails - 基於孫子屬性創建範圍

我有一個佐賀課程,裏面有許多故事,其中有許多章節,我希望佐賀有一個範圍,只有故事中的章節有傳說。 Chapter.published是一個布爾值

class Saga < ActiveRecord::Base 
    has_many :stories, -> { order(:order) } 

    def self.default_scope 
    end 
end 

class Story < ActiveRecord::Base 
    belongs_to :saga 
    has_many :chapters, -> { order(:order) } 

    def self.default_scope 
    where(saga_id: nil) 
    lambda{ where('EXISTS (SELECT 1 FROM chapters WHERE chapters.published = 1 AND chapters.story_id = stories.id)') } 
    end 
end 

class Chapter < ActiveRecord::Base 
    belongs_to :story 

    def self.default_scope 
    where(published: true) 
    end 

end 

感謝您的幫助!

回答

1

嘗試使用ActiveRecord的.joins()方法:

class Saga < ActiveRecord::Base 
    ... 
    scope :has_published_chapter, -> { 
    joins(stories: :chapters).where("chapters.published IS TRUE") 
    } 
+1

我想這應該是'連接(故事:章)''因爲有Saga'除了通過'stories'和無chapters'的'知識where子句可能是'where(chapter:{published:true})' – engineersmnky

+0

試過了,現在我有這個錯誤: 在Saga上找不到名爲'章節'的關聯;也許你拼錯了嗎? –

+0

是的,@engineersmnky發佈的內容是正確的。我將編輯... –