2016-03-15 93 views
0

我有以下查詢,我嘗試使用IN子句基於多個部門ID獲取部門表數據,但我在Rails服務器日誌中看到的查詢不正確因此數據提取失敗。問題與報價。無法使用Rails中的find_by_sql方法正確構建查詢

我在這裏嘗試了兩種不同的選擇,但他們都失敗了,因爲缺少引號或引號。

選項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') 

實際的查詢日誌中生成(用於SOEM原因追加額外的引號自動) - FAILS:

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

OPTION 2(除去QUOTES期間CSV CONVERSION)

@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子句中引號) - FAILS:

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

我該如何解決這個問題?

回答

1

嘗試將字符串拆分爲數組並將其傳遞給where子句。

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

我上面張貼不是原始查詢和原來的是更復雜的查詢。爲了解釋實際問題,我簡化了查詢。是否可以使用'find_by_sql'方法提供解決方案? – user2325154

+0

不用擔心。通過加入'@ depts.split(「」)'來實現它。非常感謝! – user2325154