将参数传递给rails上的ruby内的原始SQL查询

时间:2017-12-04 18:35:43

标签: sql ruby-on-rails ruby postgresql activerecord

我想使用rails active record执行原始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"的参数。有帮助吗?

2 个答案:

答案 0 :(得分:5)

在你的模型中添加此方法

<div [innerHTML]="myHtmlCode"></div>

这将允许您在AR模型中清理和执行任意SQL

然后只需这样做

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

答案 1 :(得分:1)

您可以在模型中执行此操作

  sql_command = <<-SQL
    SELECT address, phone, email, services
    FROM branches as b, workspaces as w
    WHERE b.workspace_id = w.id and w.name = :workspace_name
  SQL

  connection.execute(
    sanitize_sql_for_assignment([sql_command, workspace_name: "whatever"])
  )