У меня была такая же реализация, надеюсь, вы можете получить помощь.
category.rb
class Category < ApplicationRecord
has_many :category_details
end
category_detail.rb
class CategoryDetail < ApplicationRecord
belongs_to :category
scope :get_first_category_vise_details, -> {order(:category_id).group_by(&:category_id).map{|cat_detail_group| cat_detail_group.last.first} }
end
select * from categories;
+----+------+
| id | name |
+----+------+
| 1 | abc |
| 2 | xyz |
+----+------+
select * from category_details;
+----+-------------+-------------+
| id | category_id | description |
+----+-------------+-------------+
| 1 | 1 | test |
| 2 | 1 | test1 |
| 3 | 1 | test2 |
| 4 | 2 | test |
| 5 | 2 | testabc |
+----+-------------+-------------+
CategoryDetail.get_first_category_vise_details
[#<CategoryDetail id: 1, category_id: 1, description: "test">, #<CategoryDetail id: 4, category_id: 2, description: "test">]