Rails - 根据孙属性创建范围

时间:2016-09-20 17:41:24

标签: ruby-on-rails ruby model

我试图根据孙子身份为班级创建一个范围。

我有一个类Saga,它有很多故事,有许多章节,我希望佐贺有一个范围,只有故事章节的西迦出版。 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 个答案:

答案 0 :(得分:1)

尝试使用ActiveRecord的.joins()方法:

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