Search code examples
mysqlruby-on-railsrubyruby-on-rails-5

How to write named scope for sub queries in Active Record Rails


I am trying get unique records from a table based on category column.This query gives those unique records which has been tested on MYSQL. But I wanna know how to write the same thing in Rails as named scope. Can anyone let me know how to write scope for the following query in Rails 5 application:

SELECT * FROM t where id = (select min(id) from t t2 where t2.category = t.category);

Solution

  • I had a same implementation, hope you can get help.

    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">]