Skip to content

Instantly share code, notes, and snippets.

@worace
Last active August 29, 2015 14:19
Show Gist options
  • Save worace/79c93b87da1a232fb2f7 to your computer and use it in GitHub Desktop.
Save worace/79c93b87da1a232fb2f7 to your computer and use it in GitHub Desktop.
ActiveRecord Challenges

We'll be using Storedom for the following challenges.

Write ActiveRecord query statements for the following problems. You're welcome to change the schema to fit your needs. Create a gist to store your solutions.

The goal is to find the most efficient query for each piece of information, and to avoid ruby enumerables in favor of leveraging the query capabilities of SQL and ARel.

Required

group 1

  1. Find all the items that have the word "elegant" in it. (If "elegant" was not in your seeds, feel free to pick another adjective.)
  2. Find the 5 biggest orders (i.e. orders with the most items).
  3. Find the first ten orders sorted by date created.
  4. Given an item, find all of the users who have ordered that item.
  5. Find all of the orders created between yesterday and a month ago (you can use rand(1.year.ago..Time.now) in your seed file to spread out the dates a bit).

group 2

  1. Given an item. Associate it with an order without touching an OrderItem model.
  2. Find the user who has ordered the most items.
  3. Set it up so that when you destroy a user, ActiveRecord also destroys all of their orders
  4. Get the second ten orders sorted by date created.
  5. Given a collection of items, find all of the users who have ordered any of those items.

group 3

  1. Find the user who has placed the most orders.
  2. Given a collection of orders, find the users to whom those orders belong, using only one query to the database.
  3. Get the first ten users and all of their orders in one ActiveRecord query.
  4. Get all of the orders that have more than five items. Don't use Ruby.
  5. Find the most popular items (items which have been ordered the most).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment