Ruby on rails 查找中没有关联的对象有很多次
我有如下简单的课程:Ruby on rails 查找中没有关联的对象有很多次,ruby-on-rails,activerecord,many-to-many,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 :bo
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
我想找到没有分类的
书
s。如何使用where
查询?您可以使用左连接将范围
添加到您的模型中:
# 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
id | name
1 | Apple
2 | Orange
3 | Banana
colors
id | name
1 | black
2 | red
3 | yellow
和一个colors\u水果
join表:
colors_fruits
color_id | fruit_id
2 | 1 # red Apple
3 | 3 # yellow Banana
由于Rails的联接
方法生成,所有联接将只返回至少有一种颜色的果实。橙色不在列表中,因为它没有颜色(因此不可能连接):
但是当我们对没有颜色的水果感兴趣时,我们需要一个左连接。左连接
包括左表中的所有元素,即使右表中没有匹配的元素(不幸的是,这种连接没有Rails帮助程序):
这会产生如下结果:
id | color | fruit_id | color_id
1 | Apple | NULL | NULL
2 | Orange | 2 | 1
3 | Banana | 3 | 3
现在我们只需要排除那些没有color\u id
Fruits.joins('LEFT JOIN colors_fruits ON colors_fruits.fruits_id = fruits.id').
where(colors_fruits: { color_id: nil })
您可能想了解不同类型的。这是众所周知的。您可以使用左连接将范围
添加到您的模型中:
# 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
id | name
1 | Apple
2 | Orange
3 | Banana
colors
id | name
1 | black
2 | red
3 | yellow
和一个colors\u水果
join表:
colors_fruits
color_id | fruit_id
2 | 1 # red Apple
3 | 3 # yellow Banana
由于Rails的联接
方法生成,所有联接将只返回至少有一种颜色的果实。橙色不在列表中,因为它没有颜色(因此不可能连接):
但是当我们对没有颜色的水果感兴趣时,我们需要一个左连接。左连接
包括左表中的所有元素,即使右表中没有匹配的元素(不幸的是,这种连接没有Rails帮助程序):
这会产生如下结果:
id | color | fruit_id | color_id
1 | Apple | NULL | NULL
2 | Orange | 2 | 1
3 | Banana | 3 | 3
现在我们只需要排除那些没有color\u id
Fruits.joins('LEFT JOIN colors_fruits ON colors_fruits.fruits_id = fruits.id').
where(colors_fruits: { color_id: nil })
您可能想了解不同类型的。这一点是众所周知的。book\u categories
表没有book\u id
列。我正在使用一个联接表,book\u categorizations
。这行不通,但我会尝试将其转换为我需要的内容。@hattenn:我更新了答案并添加了简短的解释。book\u categories
表没有book\u id
列。我正在使用一个联接表,book\u categorizations
。这是行不通的,但我会试着把它转换成我所需要的。@hattenn:我更新了我的答案并添加了一个简短的解释。