Ruby on Rails

Active Recordでorderやpluckの中に集計関数を入れると警告が出る件

環境

Ruby 2.5.0
Rails 5.2.0

こういったSQLを発行したいときに

以下のようなコードを書くと、railsから実行時警告が出力される。

警告内容:
DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s): “SUM(id)”. Non-attribute arguments will be disallowed in Rails 6.0. This method should not be called with user-provided values, such as request parameters or model attributes. Known-safe values can be passed by wrapping them in Arel.sql(). (called from __pry__ at (pry):16)

放っておいても動くのは動くのだが、Rails 6.0ではサポートしないから直せと言われているので素直に直す。
警告内容をそのまま読み解けばわかるが、これはArel.sql()を使えば解消できる。

 
pluckなどでも同じことが起きるが、

これも、Arel.sql()を使えば警告は消える。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です