Given you have Rails e-commerce website.
There are Product and Category models which have has_and_belongs_to_many
relationship.
models/product.rb
class Product
has_and_belongs_to_many :categories
end
models/category.rb
class Category
has_and_belongs_to_many :products
end
- Create scope (function) which retrieves products which have all requested categories
1. title: '1984',
author: 'George Orwell',
rating: '5'
(categories: Dystopian, Fiction, Classic)
2. title: 'Hamlet',
author: 'William Shakespeare (Shakespeare or not Shakespeare that is the question!)',
rating: '5'
(categories: Classic)
3. title: 'The Glass Bead Game',
author: 'Hermann Hesse',
rating: '5+'
(categories: Fiction, Fantasy, and Fictional Biography)
4. title: 'The Immortal',
author: 'Jorge Luis Borges',
rating: 'BEYOUND IMAGINATION'
(categories: Fiction, Short Story)
5. title: 'The Time Machine',
author: 'H. G. Wells', rating: '5'
(categories: Fiction, Science Fiction)
6. title: 'Brave New World',
author: 'Aldous Huxley',
rating: '4'
(categories: Dystopian, Fiction, Science Fiction)
So method Product.with_categories(['Dystopian', 'Fiction'])
should return items 1 and 6.