2016-02-18 44 views
0

我正在嘗試查詢哪個父(category)記錄沒有具有給定屬性(author.id)的ha子記錄(post)。Rails 4找到缺失某些子協會的父協會

class Category < ActiveRecord::Base 
    has_many :posts, dependent: :destroy 
end 

class Post < ActiveRecord::Base 
    belong_to :category 
end 

class Author < ActiveRecord::Base 
    has_many :posts, dependent: :destroy 
end 

我試圖找出哪些類別的作者從未公佈。我們的想法是讓那些不通過給定的作家有職位類別的陣列,也可以有其他職位......只是不由特定作者提供

@author_unused_categories = @author.unused_categories 


class Author < ActiveRecord::Base 

    def unused_categories 
    categories = Categories.all 
    author_used_categories = Post.where(author_id: self.id).select(:category).uniq ?????? 
    end 
end 

回答

0
categories = Author.includes(posts: :category).select('category.id AS category_id').map(&:category_id) 

unused_categories = Category.where.not(id: categories)