LoginSignup
4

More than 5 years have passed since last update.

【Rails】RailsでSQL文を実行する方法

Posted at

実行方法

railsではfind_by_sql()メソッドでSQL文を使用することができる。
使用方法は以下のようになる。

実行方法

@video_group_name["id"] = 1
@video_name = Video.find_by_sql(['select uq_video_name from videos where fk_groups_id = ?', @video_group_name["id"]])
実行結果

<Video id: nil, uq_video_name: "001_video_wire">

find_by_sql

プレースホルダ

find_by_sql(['select uq_video_name from videos where fk_groups_id = ?', @video_group_name["id"]])

上記のようにSQL文を[]で囲むことによってプレースホルダを利用することができる。

プレースホルダとは、SQL文の中で可変な項目を後から変更可能な値として処理する方法。SQLインジェクション対策になる。

結果をハッシュとして使用する方法

find_by_sql()で返ってくる値は、Arrayクラスのインスタンスである。従って、1番目のレコードを配列からハッシュに変更して使用したい場合は以下のようにする。

Video.find_by_sql(['select uq_video_name from videos where fk_groups_id = ?', @video_group_name["id"]])[0].attributes

=> 「["id" => nil, "uq_video_name" => 002_video_wire]」

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
4