Activerecord question.. How to optimize this query..
Prefectures (have many) Cities (have many) Shops (have many) Sales (have many) Brands
I'd like to get a list of one sale per prefecture, which is yet to end.. and then list the brands available at the sale.
The nesting is making this kind of tricky for me!
Here is what I came up with, though it's pretty ugly & I think it can be optimized at the query level rather than getting all unfinished sales..
#Get all sales which are yet to finish, ordered by finish date
upcoming_sales = Sale.includes([{:shop => {:city => :prefecture}}, :brands])
.where("finish > ?", Date.today)
.order('start ASC, finish ASC')
.select(['shop.city.prefecture.name', 'brands.name'])
#filter down to a single sale per prefecture
@sales = upcoming_sales.each_with_object({}){ |s,o|
o[s.shop.city.prefecture.name] = o[s.shop.city.prefecture.name] ||= s
}