我有一个
Page
模型,其中包含许多 Section
模型,这些模型与 SectionRevision
到 current_revision
关联。从 Page
模型中,我尝试选择所有 Sections
,其中 current_revision.parent_section_id
不为零。
Section
型号:
class Section < ActiveRecord::Base
belongs_to :page
has_many :revisions, :class_name => 'SectionRevision', :foreign_key => 'section_id'
has_many :references
has_many :revisions, :class_name => 'SectionRevision',
:foreign_key => 'section_id'
belongs_to :current_revision, :class_name => 'SectionRevision', :foreign_key => 'current_revision_id'
delegate :position, to: :current_revision
def set_current_revision
self.current_revision = self.revisions.order('created_at DESC').first
end
def children
Section.includes(:current_revision).where(:section_revisions => {:parent_section_id => self.id})
end
end
和
Page
型号:
class Page < ActiveRecord::Base
belongs_to :parent, :class_name => 'Page', :foreign_key => 'parent_page_id'
has_many :children, :class_name => 'Page', :foreign_key => 'parent_page_id'
belongs_to :page_image, :class_name => 'Image', :foreign_key => 'page_image_id'
has_many :sections
validates_uniqueness_of :title, :case_sensitive => false
def top_level_sections
self.sections.includes(:current_revision).where(:section_revisions => {:parent_section_id => "IS NOT NULL"})
end
end
Page.top_level_sections
是基于: Rails where 条件使用 NOT NULL 并且当前生成一个空数组。它无法正确检测“parent_section_id”是否不为空。
如何正确书写
Page.top_level_sections
?
试试这个:
self.sections.includes(:current_revision).
where("section_revisions.parent_section_id IS NOT NULL")
这些天你会使用:
scope :top_level_sections, lambda {
sections
.includes(:current_revision)
.where.not(section_revisions: {parent_section_id: nil})
}