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?
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)
Outside your model:
ActiveRecord::Base.connection.execute(
ApplicationRecord.sanitize_sql([query, { param_1: param_1, param_2: param_2 }])
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With