2016-10-07 6 views
0

したがって、私のカテゴリにはカテゴリがあり、categoryは自己参照結合テーブルcategory_relationshipsによって多くの親と多くの子を持つことができます。以下を使用すると、これらの関係を作成および取得するときに、このすべてがうまく機能します。Rails 4:has_manyの親を持たないすべてのエントリを見つける:自己参照結合

私が今やりたいことは、親を持たないカテゴリ(基本的にすべてのトップレベルのカテゴリ)を見つけることです。

私はいくつかの異なるタイプの実装を試しましたが、適切な式を用意していません。

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 

答えて

0

私は一緒に行くことになった:

Category.joins("LEFT OUTER JOIN category_relationships ON categories.id = category_relationships.child_id").where("category_relationships.child_id IS NULL") 

けれども、私は確信してどのように効率的ではありませんよそれがある場合、または存在する場合LEFT OUTER JOINが大きなデータセットでは高価になる可能性があると私が聞いたより良い方法です。

関連する問題