Mysql 如何在活动记录Rails中为子查询编写命名范围
我正在尝试从基于category列的表中获取唯一记录。此查询提供了在MYSQL上测试过的唯一记录。但是我想知道如何在Rails中编写与命名范围相同的东西。 有人能告诉我如何在Rails 5应用程序中编写以下查询的范围吗:Mysql 如何在活动记录Rails中为子查询编写命名范围,mysql,ruby-on-rails,ruby,ruby-on-rails-5,Mysql,Ruby On Rails,Ruby,Ruby On Rails 5,我正在尝试从基于category列的表中获取唯一记录。此查询提供了在MYSQL上测试过的唯一记录。但是我想知道如何在Rails中编写与命名范围相同的东西。 有人能告诉我如何在Rails 5应用程序中编写以下查询的范围吗: SELECT * FROM t where id = (select min(id) from t t2 where t2.category = t.category); 我有一个相同的实现,希望你能得到帮助 category.rb class Category < A
SELECT * FROM t where id = (select min(id) from t t2 where t2.category = t.category);
我有一个相同的实现,希望你能得到帮助 category.rb
class Category < ApplicationRecord
has_many :category_details
end
类别_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">]
您能进一步解释一下这个查询的作用吗?我正在尝试获取每个类别值的第一条记录。id catgeory描述表数据:1 abc测试2 abc测试1 3 abc测试2 4 xyz测试5 xyz测试此查询返回记录1和记录4您是否尝试读取。将查询转换为作用域时遇到的问题,请说明您的尝试。类差异