Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在活动记录Rails中为子查询编写命名范围_Mysql_Ruby On Rails_Ruby_Ruby On Rails 5 - Fatal编程技术网

Mysql 如何在活动记录Rails中为子查询编写命名范围

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

我正在尝试从基于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 < 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您是否尝试读取。将查询转换为作用域时遇到的问题,请说明您的尝试。类差异{order:category.group_by&:category.map{{cat_detail_group}cat_detail_group.last.first.id}结束差异。get_first_category_vise_details为我提供了命名错误未定义方法'get_first_category_vise_details',因为我正在获取命名错误未定义方法'get_first_category_vise_details',因为错误您在模型差异中定义了范围get_first_category_vise_细节了吗?差异的结果是什么。回复?:首先获取类别,然后查看详细信息!谢谢顺便说一句,如果我在rails控制台上运行discience.get_first_category_vise_details,就会出现上述错误。当我使用它select语句时,它工作得很好