Rails .where() attribute IS NOT NULL
Asked Answered
C

2

8

I have a Page model containing many Section models which is associated with a SectionRevision through current_revision. From the Page model I am trying to select all Sections where the current_revision.parent_section_id is not nil.

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

And 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 is written based on: Rails where condition using NOT NULL and currently produces an empty array. It doesn't correctly detect if "parent_section_id" is not null.

How do i write Page.top_level_sections correctly?

Colligate answered 6/4, 2013 at 5:24 Comment(2)
What is the intent of Page.top_level_sections ? Is it trying to find sections that have no revisions?Glorious
Trying to find sections where current_revision.parent_section_id is not nil.Colligate
H
16

Try this:

self.sections.includes(:current_revision).
  where("section_revisions.parent_secti‌​on_id IS NOT NULL")
Huai answered 6/4, 2013 at 5:59 Comment(1)
On newer versions of AR: sections.includes(:current_revision).where.not(section_revisions: {parent_section_id: nil})Boating
U
0

These days you would use:

scope :top_level_sections, lambda {
  sections
    .includes(:current_revision)
    .where.not(section_revisions: {parent_section_id: nil})
}
Underwaist answered 8/4 at 23:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.