2013-04-06 83 views
5

我有一個Page模型,其中包含許多與SectionRevisioncurrent_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

+0

什麼是'Page.top_level_sections'的意圖是什麼?它試圖找到沒有修訂的部分? – CubaLibre 2013-04-06 05:56:37

+0

試圖找到current_revision.parent_section_id不爲零的部分。 – 2013-04-06 05:58:55

回答

10

試試這個:

self.sections.includes(:current_revision). 
    where("section_revisions.parent_secti‌​on_id IS NOT NULL") 
+0

真棒,有效。 – 2013-04-06 06:03:47

+4

在更新版本的AR:'sections.includes(:current_revision).where.not(section_revisions:{parent_section_id:nil})' – tokland 2016-08-30 21:37:59

相關問題