Ruby on rails Rails-基于孙子属性创建作用域
我正在尝试基于孙子状态为类创建一个作用域 我有一个职业传奇,有很多故事,有很多章节,我希望传奇有一个范围,只有故事中有章节的传奇才会被出版。Chapter.published是一个布尔值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
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}让适配器确定如何组装查询