sontixyou blog

技術まわり、ガジェット関連について

Rails内で直接SQLを書く方法

背景

私の中でRailsのActive RecordとSQLの相対表があまりなく、Active Recordを実行したときにどんなSQLが実行されるのかについてもっと詳しくなりたいため、勉強します。

直接SQLを実行するためには

3種類の方法はあります。

  1. execute これはクエリを実行できますが、取得結果を見ることができません。返り値のクラスは、Mysql2::Result
ActiveRecord::Base.connection.execute('select * from users')
   (4.9ms)  select * from users
=>
#<Mysql2::Result:0x000000010e6d86c0
 @query_options=
  {:as=>:array,
   :async=>false,
   :cast_booleans=>false,
   :symbolize_keys=>false,
   :database_timezone=>:utc,
   :application_timezone=>nil,
   :cache_rows=>true,
   :connect_flags=>2148540933,
   :cast=>true,
   :default_file=>nil,
   :default_group=>nil,
   :adapter=>"mysql2",
   :encoding=>"utf8mb4",
   :pool=>5,
   :database=>"sql_master_development",
   :username=>"root",
   :password=>"password",
   :host=>"127.0.0.1",
   :port=>3306,
   :flags=>2},
 @server_flags={:no_good_index_used=>false, :no_index_used=>true, :query_was_slow=>false}>
  1. select_all / select_value

こっちは、クエリを実行結果を取得することができます。

ActiveRecord::Base.connection.select_all('select * from users').rows
   (3.9ms)  select * from users
=> 
#<ActiveRecord::Result:0x000000010ec9a1f8
 @column_types={},
 @columns=["id", "name", "created_at", "updated_at", "age"],
 @hash_rows=nil,
 @rows=
  [[102, "Clementina Pagac", 2023-09-02 14:23:32.342455 UTC, 2023-09-10 08:04:33.679732 UTC, 80],
   [103, "The Hon. Vincent Kovacek", 2023-09-02 14:23:32.345886 UTC, 2023-09-10 08:04:33.688934 UTC, 5],
   [104, "Emil Anderson", 2023-09-02 14:23:32.348682 UTC, 2023-09-10 08:04:33.724766 UTC, 57],
   [105, "Cythia Rempel", 2023-09-02 14:23:32.350912 UTC, 2023-09-10 08:04:33.730596 UTC, 73],
   [106, "Clifford Wunsch", 2023-09-02 14:23:32.353071 UTC, 2023-09-10 08:04:33.733961 UTC, 39]]

# where旬で絞り込むことができる
User.connection.select_all('select * from users where age > 50')