我花了一整天的时间。
我将权限存储在postgresql数据库的一个字段中。这里的价值是“roseburg,kfc,kcpl”
我想拆分它并进行查询
select * from plant in plant in('roseburg','kfc','kcpl')
def fnc_user_permissions <br/>
temp_var = current_user.permissions.split(",")
sql_perms = String.new
# "perm1", "perm2", "perm3"
temp_var.each do |pm|
sql_perms += (sql_perms.blank? ? pm : "', '" + pm)
end
@engines = Engine.where("plant_id in (:plant_id)", {:plant_id => sql_perms })
@engines = @engines.order("name")
end
“Engine.where”添加第二个“单引号”,而不是
select * from engines where plant_id in ('roseburg', 'kfc', 'kcpl')
我得到了
select * from engines where plant_id in ('roseburg'', ''kfc'', ''kcpl')
如果我编辑每个循环到
sql_perms += (sql_perms.blank? ? pm : ", " + pm)
我得到了
select * from engines where plant_id in ('roseburg, kfc, kcpl')
我最后不得不这样做:
temp_var = current_user.permissions.split(",")
sql_perms = String.new
# "perm1", "perm2", "perm3"
temp_var.each do |pm|
sql_perms += (sql_perms.blank? ? pm : "', '" + pm)
@engines = Engine.find_by_sql("select * from engines where plant_id in ('#{sql_perms}') ")
它可以工作,但我宁愿使用.where代码 关于如何制作的任何想法.where停止添加我不想要的第二个引用?它就是微软!。
Teedub
答案 0 :(得分:1)
或者,SQL注入安全版本将是
Engine.where("plant_id in (?)", temp_var)
答案 1 :(得分:0)
你应该使用'?'将值绑定到sql语句。尝试
Engine.where("plant_id in (#{ Array.new(temp_var.size, '?').join(',') })", *temp_var)