【发布时间】: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