0
0

More than 3 years have passed since last update.

ActiveRecordで生SQLを実行して結果を配列にキャストする

Posted at

※ Railsのバージョンは5.2を想定

  1. 何はともあれ生SQLを実行するコードを書く

    result = ActiveRecord::Base.connection.select_all('SELECT x_id as id FROM users')
    
  2. 取得結果から配列にしたいSELECT結果を指定して抜き出し、新たな配列を生成する

    ids = result.map { |h| h['id'] }
    pp ids
    # [1, 2, 3, 4, 5, 6, 7]
    
0
0
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
0
0