0

I'm writing a complex ActiveRecord query that passes an ActivRecord::Relation in a pipeline of filtering functions. One of them has to add a sequence of "OR" linked conditions. As ActiveRecord::Relation does not provide the #or method I'm writing an SQL string to pass into #where. This string is generated dynamically, so I can't really use ? for values. I know from previous questions that using prepared statements is the best practice method of creating queries, but I can't find a way to apply it here.

Is there a way of escaping the strings, or converting to using prepared statements?

Edit: I'm doing something like this (the method receives items as an ActiveRecord::Relation object.

where_string = '';
filters.each do |field,value|
  if(Item.column_names.include? field)
    where_string += "OR" if where_string!=''
    where_string += " #{field} LIKE '%#{value.to_s}%'"
   end
return items.where(where_string)
4

2 回答 2

1

这是我的做法:

def filters_to_query(filters)
  filters.inject(['']) do |query, field, value|
    if Item.column_names.includes? field
      query[0] << ' OR ' unless query[0].blank?
      query[0] << "#{field} LIKE ?"
      query << value
    end
  end
end

Item.where(filters_to_query filters)
于 2013-08-16T21:18:02.220 回答
1

尝试使用以下

 query_array = []
 value_array = []
 filters.each do |field,value|
   if(Item.column_names.include? field)
     query_array << "#{field} LIKE ?"
     value_array << "%#{value.to_s}%"
   end
 end
 value_array.insert(0, query_array.join(' OR '))
 return Item.where(value_array)
于 2013-08-06T13:44:51.353 回答