Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.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 将复杂的SQL查询转换为Rails ActiveRecord表达式_Mysql_Sql_Ruby On Rails_Activerecord - Fatal编程技术网

Mysql 将复杂的SQL查询转换为Rails ActiveRecord表达式

Mysql 将复杂的SQL查询转换为Rails ActiveRecord表达式,mysql,sql,ruby-on-rails,activerecord,Mysql,Sql,Ruby On Rails,Activerecord,我有以下SQL,我似乎无法在Rails中使用活动记录对象/方法来表示 SELECT users.*, count(followings.user_id) as expr1 FROM users inner join followings on id = follows where id in (2,3,4) group by followings.follows order by expr1 desc; 显然,[2,3,4]被替换为任何ID数组 此查询执行时没有问题,并给出我想要的

我有以下SQL,我似乎无法在Rails中使用活动记录对象/方法来表示

SELECT users.*, count(followings.user_id) as expr1 FROM users 
  inner join followings on id = follows where id in (2,3,4) 
  group by followings.follows order by expr1 desc;
显然,[2,3,4]被替换为任何ID数组

此查询执行时没有问题,并给出我想要的结果。但是我很难用“ActiveRecord”的方式来表达它


如何让我的用户模型按关注者的数量进行订购?

您可以尝试以下查询:

User.select("users.*, count(followings.user_id)").joins(:followings)
.where("users.in (?)", [2,3,4]).group_by("followings.follows")

如果您遇到其他错误,请告诉我。

您的型号设置如何?我在问模型之间的关系,我假设一个用户有很多:follows,并且follows属于:User?这是一个很好的解决方案,where条件中有一个错误-但是它不能正确分组,也不能很好地与will paginate配合。相反,我不得不使用find_by_sql使其正常运行。