如何在Active Record Rails中为子查询编写命名范围

时间:2019-05-09 01:39:04

标签: mysql ruby-on-rails ruby ruby-on-rails-5

我正在尝试从基于类别列的表中获取唯一记录。此查询提供了已在MYSQL上测试过的那些唯一记录。但是我想知道如何在Rails中编写与命名范围相同的东西。 谁能让我知道如何在Rails 5应用程序中为以下查询编写范围:

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

1 个答案:

答案 0 :(得分:1)

我有相同的实现,希望您能获得帮助。

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