我是一名有用的助手,我可以翻译文本。
在 Rails 控制台中,我可以执行
我可以执行
实际上,我对 Active Record 不太熟悉,所以我甚至不确定是否有更好的方法直接通过
但是我无法理解的是,如何获取具有多个(特定)类型的所有书籍?
更新:
当前提供的答案
要获得具有所有 3 种类型而不仅仅是其中 1 种或 2 种类型的书籍,请传递什么查询?
我意识到仅凭文字来解释我的问题相当困难,因此我将使用示例来描述我所要做的事情。
例如:
#model Book
has_many: book_genres
has_many: genres, through: :book_genres
#model Genre
has_many: book_genres
has_many: books, through: :book_genres
因此,找到只属于一个流派的书籍相对比较简单,例如:
#method in books model
def self.find_books(genre)
@g = Genre.where('name LIKE ?' , "#{genre}").take
@b = @g.books
#get all the books that are of that genre
end
在 Rails 控制台中,我可以执行
Book.find_books("Fiction")
,然后将获得所有属于小说类型的书籍。但是如何查找所有既属于“青少年”又属于“小说”类型的书籍?或者如果我想查询具有 3 种类型(如“青少年”,“小说”和“浪漫”)的图书,该怎么办?我可以执行
g = Genre.where(name: ["Young Adult", "Fiction", "Romance"])
,但随后我无法执行 g.books
并获取与这三种类型相关联的所有书籍。实际上,我对 Active Record 不太熟悉,所以我甚至不确定是否有更好的方法直接通过
Books
查询,而不是找到 Genre
然后找到所有与其相关的书籍。但是我无法理解的是,如何获取具有多个(特定)类型的所有书籍?
更新:
当前提供的答案
Book.joins(:genres).where("genres.name" => ["Young Adult", "Fiction", "Romance"])
是有效的,但问题在于它返回了所有具有“青少年”OR“小说”OR“浪漫”类型的书籍。要获得具有所有 3 种类型而不仅仅是其中 1 种或 2 种类型的书籍,请传递什么查询?
ActiveRecord :: Base.connection.execute(“select * from books inner join genres on books.genre_id = genres.id where genres.name like'fiction'intersect select * from books inner join genres on books.genre_id = genres.id where genres.name like'romance'”)
。您可能需要调整内部连接条件。 - dimidintersect
,但你可以尝试使用 arel。 - dimid