Question

Hello is there a way of searching the whole array in ruby if I have the following situation.

Models: Deal, Book, Category

class Book < ActiveRecord::Base

has_and_belongs_to_many :categories
has_and_belongs_to_many :deals

end

class Category < ActiveRecord::Base
has_and_belongs_to_many :books
end

class Deal < ActiveRecord::Base
has_and_belongs_to_many :books

end

So if i do the following in the console:

Deals.first.books 

-> I get all the books which belong to the first Deal.

But now I want to get all the Books from the first deal which have for example 2 special categories. But something like this doesnt work:

Deal.first.books.all.categories.where(:name=>"Bestseller")

If I do the following:

Deal.first.books.first.categories.where(:name=>"Bestseller")

it works but gives me obviously only if the first book have this category. How can I get all books from the first deal which have the Bestseller category or even 2 categories.

Every hint or suggestion would be appreciated. Thanks!

Était-ce utile?

La solution

For single

Deal.includes(books: :categories).where(categories: {name: "Bestseller"}).books

For single / multiple

Deal.includes(books: :categories).where(categories: 
    {name: ["Bestseller","Hot Stuff"]}).books
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top