Rails .where()属性不为NULL
我有一个Page
模型,其中包含许多与SectionRevision
到current_revision
关联的Section
模型。从Page
模型中,我试图选择所有Sections
,其中current_revision.parent_section_id
不是零。Rails .where()属性不为NULL
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 condition using NOT NULL和目前生产空数组。它不能正确检测“parent_section_id”是否为空。
如何正确书写Page.top_level_sections
?
试试这个:
self.sections.includes(:current_revision).
where("section_revisions.parent_section_id IS NOT NULL")
真棒,有效。 – 2013-04-06 06:03:47
在更新版本的AR:'sections.includes(:current_revision).where.not(section_revisions:{parent_section_id:nil})' – tokland 2016-08-30 21:37:59
什么是'Page.top_level_sections'的意图是什么?它试图找到没有修订的部分? – CubaLibre 2013-04-06 05:56:37
试图找到current_revision.parent_section_id不为零的部分。 – 2013-04-06 05:58:55