Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails-基于孙子属性创建作用域_Ruby On Rails_Ruby_Model - Fatal编程技术网

Ruby on rails Rails-基于孙子属性创建作用域

Ruby on rails Rails-基于孙子属性创建作用域,ruby-on-rails,ruby,model,Ruby On Rails,Ruby,Model,我正在尝试基于孙子状态为类创建一个作用域 我有一个职业传奇,有很多故事,有很多章节,我希望传奇有一个范围,只有故事中有章节的传奇才会被出版。Chapter.published是一个布尔值 class Saga < ActiveRecord::Base has_many :stories, -> { order(:order) } def self.default_scope end end class Story < ActiveRecord::Base b

我正在尝试基于孙子状态为类创建一个作用域

我有一个职业传奇,有很多故事,有很多章节,我希望传奇有一个范围,只有故事中有章节的传奇才会被出版。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
谢谢你的帮助

尝试使用ActiveRecord的.joins方法:

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

我认为这应该是联合体::章节,因为传奇除了通过故事和where子句可以是where章节外,对章节没有任何知识:{published:true}尝试过,现在我有一个错误:在传奇中找不到名为“章节”的关联;也许你拼错了?替换为Joinstories::chapters,它正在工作!谢谢你,伙计!如果您在saga.rb模型上有很多:chapters,到::stories,那么我最初发布的内容应该是有效的……因为注释是正确的,应该是特定于数据库的,例如SQL Server likes=1 where As wherechapters:{published:TRUE}让适配器确定如何组装查询