【问题标题】:Rails 4 find parent associations which are missing certain child associationsRails 4 找到缺少某些子关联的父关联
【发布时间】:2016-02-18 01:26:38
【问题描述】:

我正在尝试查询哪些父(类别)记录没有具有给定属性(author.id)的子记录(帖子)。

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

【问题讨论】:

    标签: ruby-on-rails associations has-many


    【解决方案1】:
    categories = Author.includes(posts: :category).select('category.id AS category_id').map(&:category_id)
    
    unused_categories = Category.where.not(id: categories)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 2019-08-06
      • 1970-01-01
      相关资源
      最近更新 更多