[英]Complex Rails/Postgres SQL optimization
餐廳has_many菜
Dish
has_many Photo
Photo
belongs_to Dish
Restaurant 1
Dish 1
Photo 1 May 9, 1:00 PM
Dish 2
Photo 2 May 9, 2:00 PM
Dish 3
Photo 3 May 9, 3:00 PM
Restaurant 2
Dish 4
Photo 4 May 9, 1:00 PM
Dish 5
Photo 5 May 9, 2:00 PM
Dish 6
Photo 6 May 9, 3:00 PM
我正在嘗試檢索最新的50張照片,每家餐廳最多只能有2張菜品照片。 鑒於以上數據,我將能夠檢索ID為2、3、5 2, 3, 5, and 6
至少可以說,我當前的實現很難看。
hash = {}
bucket = []
Photo.includes(:dish => [:restaurant]).order("created_at desc").each do |p|
restaurant_id = p.dish.restaurant.id
restaurant_count = hash[restaurant_id].present? ? hash[restaurant_id] : 0
if restaurant_count < 2
bucket << p
hash[restaurant_id] = restaurant_count + 1
end
# if you've got 50 items short circuit.
end
我不禁感到有一個更有效的解決方案。 任何想法,將不勝感激 :-)。
應該有一種對查詢進行“分組”的方法,但是至少以下內容要簡單一些:
def get_photo_bucket
photo_bucket = restaurant_control = []
Photos.includes(:dish => [:restaurant]).order("created_at desc").each do |photo|
if photo_bucket.count < 50 && restaurant_control.count(photo.dish.restaurant.id) < 2
photo_bucket << photo
restaurant_control << photo.dish.restaurant.id
end
end
photo_bucket
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.