1

I am trying to get the top 5 records from each category in the items table. the items table has a category_id attribute which I want to use to select the top 5 items per category depending on the created_at attribute. so something like this pseudocode :

select top 5 from the items table
in each group
group by category_id 
top value depending on create_at column

articles I have looked at: https://stackoverflow.com/questions/32868779/get-top-n-items-per-group-in-ruby-on-rails https://stackoverflow.com/questions/32868779/get-top-n-items-per-group-in-ruby-on-rails

I want to include the associated :tags and :item_variants table so using the raw SQL with find_by_sql is not an option or ActiveRecord::Base.connection.execute(sql)

what I have tried: using raw SQL to get the records like this works. the problem is it doesn't allow includes to get the tags and item_variants associated table :

sql = "SELECT items.* rn
    FROM 
      ( SELECT  items.*,
               ROW_NUMBER() OVER (PARTITION BY name
                                  ORDER BY name DESC
                                 )
                 AS rn
        FROM items
      ) items 
    WHERE rn <= 4"

@items = Item.includes([:images_attached, :blob, :item_variants, :tags]).find_by_sql(sql)

this doesn't include the tables as mentioned and results in N+1 queries.

how can solve this guys ? thank you in advance.

Dyary
  • 11
  • 2

0 Answers0