Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.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
Sql Rails:如何找出哪个父对象具有最多的子记录_Sql_Ruby On Rails_Rails Activerecord - Fatal编程技术网

Sql Rails:如何找出哪个父对象具有最多的子记录

Sql Rails:如何找出哪个父对象具有最多的子记录,sql,ruby-on-rails,rails-activerecord,Sql,Ruby On Rails,Rails Activerecord,这是我正在使用的两个模型 用户模型 class User < ActiveRecord::Base has_many :products end class Product < ActiveRecord::Base belongs_to :user end class用户

这是我正在使用的两个模型

用户模型

class User < ActiveRecord::Base
  has_many :products
end
class Product < ActiveRecord::Base
  belongs_to :user
end
class用户
产品型号

class User < ActiveRecord::Base
  has_many :products
end
class Product < ActiveRecord::Base
  belongs_to :user
end
类产品
现在我想知道哪个用户拥有最多的产品

我知道我可以通过为用户和相关产品构建一个循环来找到答案,但是有没有办法通过活动记录查询来找到答案呢?

Product.select(:user\u id).group(:user\u id).order(:user\u id).order(“count(user\u id)desc”)。首先,user
可以是一个解决方案

Product.select(:user\u id).group(:user\u id).order(“count(user\u id)desc”).首先。用户
可以是解决方案