Skip to content

Instantly share code, notes, and snippets.

@taras2358
Last active March 22, 2017 11:33
Show Gist options
  • Save taras2358/e76a8a0d8480488bdb6b33c0f931fa41 to your computer and use it in GitHub Desktop.
Save taras2358/e76a8a0d8480488bdb6b33c0f931fa41 to your computer and use it in GitHub Desktop.
Rails e-commerce exercise

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

Task:

  • Create scope (function) which retrieves products which have all requested categories

Example:

Products:

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment