Skip to content

Instantly share code, notes, and snippets.

@worace
Last active August 29, 2015 14:19
Show Gist options
  • Save worace/88643691d139d5f78f0f to your computer and use it in GitHub Desktop.
Save worace/88643691d139d5f78f0f to your computer and use it in GitHub Desktop.
active record challenge solutions

Find all the items that have the word "elegant" in it. (If "elegant" was not in your seeds, feel free to pick another adjective.)

Item.where("items.name LIKE '%Fantastic%'")

Find the 5 biggest orders (i.e. orders with the most items).

OrderItem.group(:order_id).order("count(id) desc").limit(5).pluck(:order_id)

Find the first ten orders sorted by date created.

Order.order(:created_at).limit(10)

Given an item, find all of the users who have ordered that item.

OrderItem.joins(:order).where(item_id: 20).pluck(:user_id)

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).

Order.where("created_at < ? AND created_at > ?", 1.day.ago, 30.days.ago)

Given an item. Associate it with an order without touching an OrderItem model.

Item.last.orders << Order.last

Find the user who has ordered the most items.

Order.joins(:order_items).group(:user_id).order("count('order_items.id') desc").limit(1).pluck(:user_id)

Set it up so that when you destroy a user, ActiveRecord also destroys all of their orders

class User < ActiveRecord::Base
  has_many :orders, dependent: :destroy
end

Get the second ten orders sorted by date created.

Order.order(:created_at).limit(10).offset(10)

Given a collection of items, find all of the users who have ordered any of those items.

Item.where(id: [5,20,11]).joins(:order_items).joins(:orders).pluck(:user_id)

Find the user who has placed the most orders

User.joins(:orders).group(:user_id).order('count("orders.id") desc')

Given a collection of orders, find the users to whom those orders belong, using only one query to the database.

User.joins(:orders).where("orders.id in (1,2,3,4)").pluck(:id)

Get the first ten users and all of their orders in one ActiveRecord query

User.includes(:orders).limit(10)

Get all of the orders that have more than five items. Don't use Ruby.

Find the most popular items (items which have been ordered the most).

Item.joins(:order_items).group(:item_id).order("count('order_items.id') desc").limit(10).pluck(:id)

Find the most popular item (item which has been ordered most)

Item.joins(:order_items).group(:item_id).order("count(item_id) desc").first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment