LoginSignup
0
1

More than 3 years have passed since last update.

【Rails】SQL文を直接実行する

Posted at

ActiveRecordを使わずに、自分で作成したSQL文を使ってDBに問い合わせをする方法です。

name = 'サンプル太郎'
email = 'tarou@example.com'
now = Time.zone.now
args = ['INSERT INTO users (name, email, created_at, updated_at) VALUES (?, ?, ?, ?)', name, email, now, now] #下準備
sql = ActiveRecord::Base.send(:sanitize_sql_array, args) #sql文を作成
ActiveRecord::Base.connection.execute(sql) #sql文を実行

注意点

  • 謎の戻り値が返ってくるので、SELECTはできません。
  • 実行速度やサーバーへの負荷をかなり抑えることができますが、バリデーションや外部キー制約が効かなくなるなど懸念点も多いので注意が必要です。
  • いわゆる「Railsのレール」からは外れた実装だと思うので、ActiveRecordではどうにもならない時にだけ使う感じです。
0
1
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
1