Techioz Blog

Ruby on Rails 内の生の SQL クエリにパラメータを渡す

概要

Rails アクティブ レコードを使用して生の SQL クエリを実行したいのですが、クエリはパラメータを受け取るため、そのパラメータをクエリ文字列に安全に渡す適切な方法が見つかりません。クエリは次のとおりです

def self.get_branches_by_workspace_name(workspace_name)
  branches = ActiveRecord::Base.connection.execute("
    select
      address,
      phone,
      email,
      services
    from branches as b, workspaces as w
    where b.workspace_id = w.id and w.name= :workspace_name", workspace_name).to_a
  return branches
end

「workspace_name」という名前のパラメータを渡したいと思います。何か助けはありますか?

解決策

モデルにこのメソッドを追加します

  def self.execute_sql(*sql_array)     
   connection.execute(sanitize_sql_array(sql_array))
  end

これにより、AR モデルで任意の SQL をサニタイズして実行できるようになります。

次に、次のようなものを実行して SQL を実行し、クエリによって返される行ごとに 1 つずつハッシュの配列を返します。

ModelName.execute_sql("select address,phone,email,services from branches as b, workspaces as w 
    where b.workspace_id = w.id and w.name= ?", workspace_name)

# => [{"address"=>"...","phone"=>"...","email"=>"...","services"=>"..."}, ...]