2017-12-04 11 views
2

rails active recordを使用して未処理のSQLクエリを実行したいが、クエリにパラメータが必要なので、クエリ文字列にそのパラメータを安全に渡す適切な方法が見つからない。クエリは次のようになります。レール上のRuby内の生の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」という名前のパラメータを渡します。どんな助け?お使いのモデルで

答えて

4

は、単にそれが働いていたこの

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) 
+0

を行う。これは、あなたがサニタイズせて、ARモデル

で任意のSQLを実行します。この方法

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

を追加します。ありがとうございました! –

+1

うれしい私はいくつかの援助の可能性があります:Dハッピーコーディングマン! – Ishtiaque05

関連する問題