0

我花了一整天的时间在这上面。
我将权限存储在 postgresql 数据库的一个字段中。这里的值是“roseburg,kfc,kcpl”我想拆分它并让查询选择 * from engine where plant_id 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 停止添加我不想要的第二个引号的任何想法?它是如此微软!

提杜布

4

2 回答 2

1

或者,这个的 SQL 注入安全版本将是

Engine.where("plant_id in (?)", temp_var)
于 2013-01-02T18:09:23.440 回答
0

你应该使用'?将值绑定到 sql 语句。尝试

Engine.where("plant_id in (#{ Array.new(temp_var.size, '?').join(',') })", *temp_var)
于 2012-09-11T17:52:48.950 回答