查找has_many_through中未关联的对象

时间:2015-11-22 11:51:02

标签: ruby-on-rails activerecord many-to-many

我有这样的简单类:

class Book
  has_many :book_categorizations
  has_many :categories, through: :book_categorizations, source: :book_category
end

class BookCategorizations
  belongs_to :book
  belongs_to :book_category
end

class BookCategory
  has_many :book_categorizations
  has_many :books, through: :book_categorizations
end

我想找到没有类别的Book。如何使用where查询?

1 个答案:

答案 0 :(得分:3)

您可以将scope添加LEFT JOIN到您的模型中:

# in book.rb
scope :without_categories, lambda {
  joins('LEFT JOIN book_categorizations ON books.id = book_categorizations.book_id').
    where(book_categorizations: { book_category_id: nil })
}

可以使用:

Book.without_categories
#=> returns books without a category

工作原理:

成像您有一个fruits和一个colors表:

fruits
id | name
 1 | Apple
 2 | Orange
 3 | Banana

colors
id | name
 1 | black
 2 | red
 3 | yellow

colors_fruits联接表:

colors_fruits
color_id | fruit_id
2        | 1           # red Apple
3        | 3           # yellow Banana

自从Rails' joins方法生成INNER JOIN,所有连接只会返回至少有一种颜色的水果。橙色不在列表中,因为它没有颜色(因此无法连接):

Fruit.joins(:colors)
#=> red Apple, yellow Banana (simplified)

但是当我们对没有颜色的水果感兴趣时,我们需要一个LEFT JOINLEFT JOIN包括左表中的所有元素 - 即使右表没有匹配(遗憾的是这种连接没有Rails助手):

Fruits.joins('LEFT JOIN colors_fruits ON colors_fruits.fruits_id = fruits.id')

这会产生如下结果:

id | color  | fruit_id | color_id
 1 | Apple  | NULL     | NULL
 2 | Orange | 2        | 1
 3 | Banana | 3        | 3

现在我们只需要排除没有color_id

的那些
Fruits.joins('LEFT JOIN colors_fruits ON colors_fruits.fruits_id = fruits.id').
       where(colors_fruits: { color_id: nil })

您可能想了解不同类型的SQL JOINS。这是众所周知的diagram about joins