2016-10-07 37 views
0

所以我的設置是我有類別,並且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 

回答

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在較大的數據集上可能會很昂貴。

相關問題