14
11

More than 5 years have passed since last update.

Railsのfind_by_sqlで取得できるモデルからは、select句で指定した名前で値が取れる

Last updated at Posted at 2015-02-09

生のSQLを使ってデータを集計する場合、COUNT(*)などの項目は、モデルに対応する属性がありません。
なので集計とかする場合はselect_allを使ってハッシュの配列で取得するしかないと思ってました。

コンソール
[50] pry(main)> sql = %q/select author, count(*) as count from contents group by author/
[51] pry(main)> Article.connection.select_all(sql).to_a                            
=> [{"author"=>"Jirou", "count"=>1}, {"author"=>"Tarou", "count"=>1}]

find_by_sqlで取得すると、以下のようにcount(*)で取得した件数の値が見えないので、取得できないものと思いこんでいたのですね。

コンソール
[52] pry(main)> Article.find_by_sql(sql).to_a
=> [#<Article:0x007fc9d2e63478 id: nil, author: "Jirou">,
 #<Article:0x007fc9d2e631a8 id: nil, author: "Tarou">]

しかしattributesメソッドで属性を確認してみると

コンソール
[53] pry(main)> Article.find_by_sql(sql).first.attributes
=> {"author"=>"Jirou", "count"=>1, "id"=>nil}
                       ^^^^^^^^^^^

取得できていました!

コンソール
[54] pry(main)> Article.find_by_sql(sql).first.count
=> 1

find_by_sqlのselect句に指定した項目で、対象となるモデルの属性に無いものは、特異メソッドとして属性が追加されてくるんですね。
知らなかったー。

14
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
11