问题
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