-
Find all the items that have the word "elegant" in it.
Item.all.where("name LIKE ?", "%elegant%")
-
Add three orders to a user.
user = User.last
3.times { Order.create(amount: 1000, user_id: user) }
or
user = User.find(1)
user.orders.create(amount: 5)
- Given an item. Associate it with an order without touching an OrderItem model.
item = Item.last
order = Order.last
order.items << item
or
i = Item.first
o = Order.last
i.orders << o
- Find the most popular items.
Item.joins(:order_items).group("order_items.item_id").order("count(order_items.item_id) DESC").take(amount)
Item.joins(:order_items).select('items.*, count(item_id) as "item_count"').group(:item_id).order(' item_count desc')
val = Item.joins
or can use counter_cache
belongs_to :item, counter_cache: true
and add order_items_count:integer
to migration
-
Find the biggest orders (in terms of items). ``
-
Find the user who has ordered the most items.
User.joins(orders: :order)items).select("users.*, count(order_items.item_id) as items_count").order("items_count desc")
Order.joins(:order_items).select("orders.*, count(order_items.item_id) as 'order_items_count'").order("order_items_count desc").first.user_id
-
Find the user who has placed the most orders. ``
-
Find the first ten orders sorted by date created. Don't use Ruby
Order.order(:created_at).limit(10)
-
Get the second ten orders sorted by date created. Don't use Ruby.
Order.order(:created_at).limit(10).offset(10)
-
Given a collection of orders, return a collection of the users who those orders belong to, using only one query to the database.
Order.select(:user_id)
orOrder.pluck(:user_id)
(pluck won't return an ActiveRecord relation, though) -
Given an item, find all of the users who have ordered that item.
Item.first.orders.pluck(:user_id)
-
Get the first ten users and all of their orders in one ActiveRecord query.
User.includes(:orders).limit(10)
-
Given a collection of items, find all of the users who have ordered that item.
order_ids = items.flat_map(&:order_items).map(&:order_id)
user_ids = Order.where(id: order_ids).pluck(:user_id)
uhhhhhhh
-
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: 1.month.ago..1.day.ago)
Order.where(created_at: (Time.now - 30.day)..Time.now)
-
Set it up so that when you destroy a user, ActiveRecord also destroys all of their orders
has_many :orders, dependent: :destroy