2013-04-06 10 views
5

Ho un modello Page contenente molti modelli Section associato a SectionRevision tramite current_revision. Dal modello Page sto provando a selezionare tutto Sections in cui lo current_revision.parent_section_id non è nullo.Attributo Rails .where() IS NOT NULL

Section modello:

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 

E Page modello:

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 è scritta in base: Rails where condition using NOT NULL e attualmente produce un array vuoto. Non rileva correttamente se "parent_section_id" non è nullo.

Come si scrive Page.top_level_sections correttamente?

+0

Qual è l'intento di 'Page.top_level_sections'? Sta cercando di trovare sezioni che non hanno revisioni? – CubaLibre

+0

Cercando di trovare le sezioni dove current_revision.parent_section_id non è nullo. –

risposta

10

Prova questo:

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

Impressionante che funzioni. –

+4

Nelle versioni più recenti di AR: 'sections.includes (: current_revision) .where.not (section_revisions: {parent_seection_id: nil})' – tokland

Problemi correlati