0

レストラン 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

レストランごとに料理の写真を 2 枚に制限して、最新の 50 枚の写真を取得しようとしています。上記のデータがあれば、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

もっと効率的な解決策があると感じずにはいられません。任意のアイデアをいただければ幸いです:-)。

4

1 に答える 1

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
于 2013-05-09T13:35:22.280 に答える