Rails:没有任何关联具有某个值

时间:2018-05-03 17:01:35

标签: ruby-on-rails tags associations has-and-belongs-to-many

我有书和标签。

def Book < ApplicationRecord
  has_and_belongs_to_many :tags
end

def Tag < ApplicationRecord
  has_and_belongs_to_many :books
end

我想找到所有的图书都有关联 id 1 的标签。 (他们可能没有标签。)我试过这个:

Book.includes(:tags).where.not(tags: { id: 1 })

此查询会查找所有没有标签的图书,包含其他标签的图书以及具有不需要的标记的图书以及与其关联的至少一个其他标记

如何使用特定代码过滤所有图书?谢谢你的任何想法!

2 个答案:

答案 0 :(得分:2)

应用/模型/ books_tag.rb

class BooksTag < ApplicationRecord
  belongs_to :book
  belongs_to :tag
end

<强>解决方案:

Book.where.not(id:
  BooksTag.where(tag_id: 1).select(:book_id)
)
  • 与Anton的答案类似,我想不出只有一个查询解决方案。
  • 我在上面添加了books_tag模型,因此我们不需要进行JOIN SQL查询。

答案 1 :(得分:0)

快速解决方案是提出2个请求。首先,您将获得所有具有相关标签的图书ID,然后您选择所有其他图书。

unwanted_book_ids = Books.joins(:tags).where(tags: { id: 1 }).pluck('books.id').uniq
@books = Book.where.not(id: unwanted_book_ids)

我不确定它是最好的解决方案,但是,说实话,我找不到任何没有子查询/联合/等的琐碎的