【问题标题】:Not able to build query correctly using the find_by_sql method in Rails无法使用 Rails 中的 find_by_sql 方法正确构建查询
【发布时间】:2016-03-15 19:34:42
【问题描述】:

我有以下查询,我试图使用IN 子句根据多个部门ID 获取部门表数据,但我在Rails 服务器日志中看到的查询不正确,因此数据获取失败。引号有问题。

我在这里尝试了两个不同的选项,但是由于缺少引号或多余的引号,它们都失败了。

选项 1(在 CSV 转换期间添加引号)

@depts = current_user.depts             
puts @depts                 # prints    IT Account Finance

# converting to CSV string here
@dept_ids_csv = @depts.gsub(" ", "','")     
puts @dept_ids_csv          # prints    IT','Account','Finance


@dept_data = Department.find_by_sql(["select * from departments a where a.dept_id in (?)", @dept_ids_csv])

预期的查询日志:

select * from departments a where a.dept_id in ('IT','Account','Finance')

生成的实际查询日志(出于某些原因会自动附加额外的引号) - 失败:

select * from departments a where a.dept_id in ('IT'',''Account'',''Finance')

选项 2(在 CSV 转换期间删除引号)

@depts = current_user.depts             
puts @depts                 # prints    IT Account Finance

# converting to CSV string here 
@dept_ids_csv = @depts.gsub(" ", ",")   
puts @dept_ids_csv          # prints    IT,Account,Finance


@dept_data = Department.find_by_sql(["select * from departments a where a.dept_id in (?)", @dept_ids_csv])

预期的查询日志:

select * from departments a where a.dept_id in ('IT','Account','Finance')

生成的实际查询日志(IN 子句中缺少引号) - 失败:

select * from departments a where a.dept_id in ('IT,Account,Finance')

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby csv activerecord rails-activerecord


    【解决方案1】:

    尝试将字符串拆分为数组并将其传递给 where 子句。

    @dept_data = Department.where(dept_id: @depts.split(" "))
    

    【讨论】:

    • 我在上面发布的查询不是原始查询,因为原始查询更复杂。我已经简化了查询以解释实际问题。您是否可以使用find_by_sql 方法提供解决方案?
    • 不用担心。通过输入@depts.split(" ") 让它工作。非常感谢!
    【解决方案2】:

    .split(' ')把字符串转成数组怎么样?

    例子:

    @emails = ['spree@example.com', 'test@gmail.com']
    
    User.find_by_sql(["SELECT * FROM spree_users WHERE email IN (?)", @emails])
    

    给予

    SELECT * FROM users WHERE email IN ('spree@example.com','test@gmail.com')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-06
      • 2011-08-08
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      相关资源
      最近更新 更多