Mysql 将复杂的SQL查询转换为Rails ActiveRecord表达式
我有以下SQL,我似乎无法在Rails中使用活动记录对象/方法来表示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数组 此查询执行时没有问题,并给出我想要的
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使其正常运行。