Итак, у меня есть категории, и у category
может быть много родителей и много детей через таблицу ссылочного ссылочного category_relationships
. Используя ниже, все это отлично работает при создании и извлечении этих отношений.Rails 4: Найти все записи без родителей в has_many: хотя самореферентное объединение
Что бы я хотел сделать сейчас, это найти категории, в которых нет родителей (в основном все категории верхнего уровня).
Я пробовал несколько различных реализаций типа where.not
, но просто не придумал правильное выражение.
category.rb
# == Schema Information
#
# Table name: categories
#
# created_at :datetime not null
# id :integer not null, primary key
# name :string(255) not null
# updated_at :datetime not null
#
class Category < ActiveRecord::Base
# CategoryRelationships (Parents & Children)
# ==========================================================================================================
has_many :parent_child_relationships,
class_name: "CategoryRelationship",
foreign_key: :child_id,
inverse_of: :parent,
dependent: :destroy
has_many :parents,
through: :parent_child_relationships,
source: :parent
has_many :child_parent_relationships,
class_name: "CategoryRelationship",
foreign_key: :parent_id,
inverse_of: :child,
dependent: :destroy
has_many :children,
through: :child_parent_relationships,
source: :child
end
category_relationships.rb
# == Schema Information
#
# Table name: category_relationships
#
# child_id :integer not null
# created_at :datetime not null
# id :integer not null, primary key
# parent_id :integer not null
# updated_at :datetime not null
#
class CategoryRelationship < ActiveRecord::Base
# Parent (Category)
# ==========================================================================================================
belongs_to :parent,
class_name: "Category",
inverse_of: :parent_child_relationships
# Child (Category)
# ==========================================================================================================
belongs_to :child,
class_name: "Category",
inverse_of: :child_parent_relationships
# Validations
# ==========================================================================================================
validates :parent,
presence: true
validates :child,
presence: true
end