2013-04-06 12 views
5

Mam model Page zawierający wiele modeli Section, który jest powiązany z SectionRevision do current_revision. Z modelu Page próbuję wybrać wszystkie Sections, gdzie current_revision.parent_section_id nie jest zerowy.Argument Rails .where() NIE JEST NULL

Section model:

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 

I Page model:

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 został napisany w oparciu o: Rails where condition using NOT NULL i produkuje obecnie pustą tablicę. Nie wykrywa poprawnie, czy "parent_section_id" nie ma wartości null.

Jak poprawnie napisać Page.top_level_sections?

+0

Co jest intencją 'Page.top_level_sections'? Czy próbuje znaleźć sekcje, które nie mają poprawek? – CubaLibre

+0

Próba znalezienia sekcji, w której current_revision.parent_section_id nie jest zerowa. –

Odpowiedz

10

Spróbuj tego:

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

Fantastyczny, który działa. –

+4

W nowszych wersjach AR: 'sections.includes (: current_revision) .where.not (section_revisions: {parent_section_id: zero})) – tokland