Ruby on rails 如何仅列出没有子类别的页面?

Ruby on rails 如何仅列出没有子类别的页面?,ruby-on-rails,ruby,Ruby On Rails,Ruby,目前,页面也可以是子类别,因此当我调用页面上的相关子类别时,它会检查页面是否是子类别 我如何迭代只显示非子类别的页面 class Page < ApplicationRecord extend FriendlyId friendly_id :name, use: :slugged has_and_belongs_to_many :subcategories, class_name: "Page", join_table: "subcategories",

目前,页面也可以是子类别,因此当我调用页面上的相关子类别时,它会检查页面是否是子类别

我如何迭代只显示非子类别的页面

class Page < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: :slugged

  has_and_belongs_to_many :subcategories,
    class_name: "Page",
    join_table: "subcategories",
    foreign_key: "page_id",
    association_foreign_key: "other_page_id"

  has_and_belongs_to_many :related_subcategories,
    class_name: "Page",
    join_table: "subcategories",
    foreign_key: "other_page_id",
    association_foreign_key: "page_id"


end
类页
您想要范围查询吗

也许是这样的:

class Page < ApplicationRecord
extend FriendlyId
  friendly_id :name, use: :slugged

  has_and_belongs_to_many :subcategories,
    class_name: "Page",
    join_table: "subcategories",
    foreign_key: "page_id",
    association_foreign_key: "other_page_id"

  has_and_belongs_to_many :related_subcategories,
    class_name: "Page",
    join_table: "subcategories",
    foreign_key: "other_page_id",
    association_foreign_key: "page_id"

  scope :not_subcategoried, -> { where('related_subcategories_count = ?',0) }
类页{where('related_subcategories_count=?',0)}
Page.joins("RIGHT JOIN subcategories ON pages.id = subcategories.other_page_id").where("subcategories.other_page_id IS NULL")