【问题标题】:Passing parameters to raw SQL queries inside ruby on rails将参数传递给 ruby​​ on rails 中的原始 SQL 查询
【发布时间】:2018-05-18 07:08:57
【问题描述】:

我想使用 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”的参数。有什么帮助吗?

【问题讨论】:

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


    【解决方案1】:

    在你的模型中添加这个方法

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

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

    然后简单地这样做

    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)
    

    【讨论】:

    • 为什么需要sendsanitize_sql_array 方法受到保护。
    【解决方案2】:

    在你的模型中你可以这样做

      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"])
      )
    

    【讨论】:

      【解决方案3】:

      在你的模型之外:

      ActiveRecord::Base.connection.execute(
        ApplicationRecord.sanitize_sql([query, { param_1: param_1, param_2: param_2 }])
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-21
        • 2020-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-24
        • 2021-10-10
        相关资源
        最近更新 更多