rails:コンソールから生SQLを実行する

以下のように、rails consoleから生SQL実行できる。
戻り値がActiveRecord::Resultなので、hash化すると見やすい。
(hash化しなくても見れる)

sql = 'SELECT staff_type, count(*) FROM staffs where is_valid = true group by staff_type order by staff_type'
ActiveRecord::Base.connection.select_all(sql).to_hash

結果0件の場合は、to_hashだとエラーになるので注意

以下でも実行できるが、クエリーの結果をのぞくには扱いにくい。

ActiveRecord::Base.connection.execute(sql)