Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.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
如何在Ruby中替换此SQL查询,以便只使用ActiveRecord代码?_Sql_Ruby_Activerecord - Fatal编程技术网

如何在Ruby中替换此SQL查询,以便只使用ActiveRecord代码?

如何在Ruby中替换此SQL查询,以便只使用ActiveRecord代码?,sql,ruby,activerecord,Sql,Ruby,Activerecord,这实际上是可行的(它返回数据库中曲目数量最多的5位艺术家) 但发出以下警告: 弃用警告:危险的查询方法(其参数为 作为原始SQL)使用非属性参数调用:“COUNT(*) 描述”。Rails 6.1中不允许使用非属性参数。这 方法不应使用用户提供的值(如请求)调用 参数或模型属性。已知的安全值可以通过 将它们包装在Arel.sql()中。(由五大顶级艺术家在 /home/maxichabaud/code/maxichabaud/fullstack challenges/03 AR数据库/03 Ac

这实际上是可行的(它返回数据库中曲目数量最多的5位艺术家)

但发出以下警告:

弃用警告:危险的查询方法(其参数为 作为原始SQL)使用非属性参数调用:“COUNT(*) 描述”。Rails 6.1中不允许使用非属性参数。这 方法不应使用用户提供的值(如请求)调用 参数或模型属性。已知的安全值可以通过 将它们包装在Arel.sql()中。(由五大顶级艺术家在 /home/maxichabaud/code/maxichabaud/fullstack challenges/03 AR数据库/03 ActiveRecord基础知识/Optional-01-Mapping-Existing-Database/app/querys.rb:18)

如何重构“COUNT(*)DESC”行?

您可以尝试以下方法:

def top_five_artists(genre_name)
  Artist.joins(albums: { tracks: :genre })
        .where(genres: { name: genre_name })
        .group(:name)
        .order(Arel.sql('count(*) DESC'))
        .limit(5)
end

首先,您可以使用
order(Arel.sql('count(*)DESC'))
来消除上面提到的不推荐使用的警告,然后,您可以将代码编写成多行,这样RuboCop就不会因为“这行太长”而困扰您了。

我认为这是的重复,因为我想不出如何按
count(*)排序desc
而不会陷入一堆难以理解的AREL代码。因此,您可以
order(Arel.sql('count(*)desc'))
来消除警告。虽然此代码块可能会回答这个问题,但最好能提供一点解释,说明它为什么会这样做。
def top_five_artists(genre_name)
  Artist.joins(albums: { tracks: :genre })
        .where(genres: { name: genre_name })
        .group(:name)
        .order(Arel.sql('count(*) DESC'))
        .limit(5)
end