Rails filtering records in many to many relationship

旧时模样 提交于 2019-12-11 04:14:04

问题


I have many to many relationship for books and authors like:

class Book < ApplicationRecord
  has_many :books_authors, inverse_of: :author, dependent: :destroy
  has_many :authors, through: :books_authors
end

class Author < ApplicationRecord
  has_many :books_authors, dependent: :destroy
  has_many :books, through: :books_authors
end

class AuthorsBook < ApplicationRecord
  belongs_to :author
  belongs_to :book
end

Now to get all the Books with Authors of ids: 1 and 3 The query is like :

Book.joins(:authors).where(authors: {id:  [1, 3]}).uniq

Book.joins(:books_authors).where(books_authors: {author_id:  [1,3]}).uniq

Book.joins(:authors).where('authors.id IN (?)', [1,3]).uniq 

But I get a book whose authors' ids are 2,3,5, which should not be the case, as it does not have author with id 1.

So , how could I only get the books with given authors ids?


回答1:


You need a having clause in there combined with your where clause:

ids = [1,3]
Book
  .select('books.*') # not sure if this is necessary
  .where(authors_books: { author_id: ids })
  .joins(:authors_books)
  .group('books.id')
  .having('count(authors_books) >= ?', ids.size)

The SQL: https://www.db-fiddle.com/f/i7TXPJgavLwQCHb4GhgH3b/0



来源:https://stackoverflow.com/questions/54260550/rails-filtering-records-in-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!