Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to raw SQL queries inside ruby on rails

I want to execute a raw SQL query using rails active record, but my query takes a parameter, I can't find a proper way to safely pass that parameter into the query string. The query is as follows

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

I would like to pass a parameter named "workspace_name". Any help?

like image 889
Sayed Alesawy Avatar asked Feb 05 '23 03:02

Sayed Alesawy


2 Answers

In your model add this method

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

This will let you sanitize and execute arbitrary SQL in an AR model

Then simply do this

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)
like image 138
Ishtiaque05 Avatar answered Feb 07 '23 00:02

Ishtiaque05


Outside your model:

ActiveRecord::Base.connection.execute(
  ApplicationRecord.sanitize_sql([query, { param_1: param_1, param_2: param_2 }])
)
like image 29
user3033467 Avatar answered Feb 07 '23 01:02

user3033467