2013-04-06 19 views
5

SectionRevisioncurrent_revisionに関連付けられたSectionモデルを含むPageモデルがあります。 Pageモデルから、私はcurrent_revision.parent_section_idがゼロでないすべてのSectionsを選択しようとしています。Rails .where()属性がIS NOT 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"がnullでない場合、正しく検出されません。

Page.top_level_sectionsを正しく書き込むにはどうすればよいですか?

+0

'Page.top_level_sections'の意図は何ですか?リビジョンのないセクションを見つけようとしていますか? – CubaLibre

+0

current_revision.parent_section_idがnilでないセクションを見つけようとしています。 –

答えて

10

これを試してみてください:

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

素晴らしいです。 –

+4

新しいバージョンのARでは 'sections.includes(:current_revision).where.not(section_revisions:{parent_section_id:nil})' – tokland