Complex Rails/Postgres SQL optimization -


restaurant 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 

i'm trying retrieve latest 50 photos limit of 2 dish photos per restaurant. given data above i'd able retrieve photos ids 2, 3, 5, , 6

my current implementation ugly least.

hash = {} bucket = [] photo.includes(:dish => [:restaurant]).order("created_at desc").each |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 

i can't feel there's more efficient solution. ideas appreciated :-).

there should way of 'grouping' query, @ least following bit simpler:

def get_photo_bucket   photo_bucket = restaurant_control = []   photos.includes(:dish => [:restaurant]).order("created_at desc").each |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 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -