复杂的Rails / Postgres SQL优化

时间:2013-05-09 12:46:01

标签: sql ruby-on-rails ruby ruby-on-rails-3 postgresql

餐厅     has_many Dish

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, 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

我不禁觉得有一个更有效的解决方案。任何想法将不胜感激: - )。

1 个答案:

答案 0 :(得分:1)

应该有一种“分组”查询的方法,但至少以下内容有点简单:

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