【发布时间】:2016-10-07 18:50:30
【问题描述】:
所以我的设置是我有类别,category 可以通过自引用连接表category_relationships 有许多父母和许多孩子。使用下面的内容,在创建和检索这些关系时,这一切都很好。
我现在想做的是,找到没有任何父类的类别(基本上所有顶级类别)。
我尝试了几种不同的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
【问题讨论】:
标签: ruby-on-rails has-many-through self-reference