简体   繁体   English

将参数传递给SQL查询

[英]Passing params to sql query

So, in my rails app I developed a search filter where I am using sliders. 因此,在我的rails应用程序中,我开发了一个使用滑块的搜索过滤器。 For example, I want to show orders where the price is between min value and max value which comes from the slider in params. 例如,我想显示价格介于最小值最大值之间的订单,这些价格来自参数中的滑块。 I have column in my db called "price" and params[:priceMin], params[:priceMax]. 我的数据库中有列“价格”和params [:priceMin],params [:priceMax]。 So I can't write something kinda MyModel.where(params)... . 所以我不能写一些MyModel.where(params)...东西。 You may say, that I should do something like MyModel.where('price >= ? AND price <= ?', params[:priceMin], params[:priceMax]) but there is a problem: the number of search criteria depends on user desire, so I don't know the size of params hash that passes to query. 您可能会说,我应该做类似MyModel.where('price >= ? AND price <= ?', params[:priceMin], params[:priceMax])但是有一个问题:搜索条件的数量取决于根据用户的需求,所以我不知道传递给查询的参数哈希的大小。 Are there any ways to solve this problem? 有什么办法可以解决这个问题?

UPDATE 更新

I've already done it this way 我已经这样做了

def query_senders
query = ""
if params.has_key?(:place_from)
  query += query_and(query) + "place_from='#{params[:place_from]}'"
end
if params.has_key?(:expected_price_min) and params.has_key?(:expected_price_max)
      query += query_and(query) + "price >= '#{params[:expected_price_min]}' AND price <= '#{params[:expected_price_max]}'"
end...

but according to ruby guides ( http://guides.rubyonrails.org/active_record_querying.html ) this approach is bad because of SQL injection danger. 但是根据ruby指南( http://guides.rubyonrails.org/active_record_querying.html ),这种方法很糟糕,因为存在SQL注入的危险。

You can get the size of params hash by doing params.count . 您可以通过执行params.count来获取params hash的大小。 By the way you described it, it still seems that you will know what parameters can be passed by the user. 通过你所描述的方式,它似乎仍然认为你会知道什么参数可以由用户通过。 So just check whether they're present, and split the query accordingly. 因此,只需检查它们是否存在,然后相应地拆分查询。

Edited: 编辑:

def query_string
  return = {}
  if params[:whatever].present?
     return.merge({whatever: #{params[:whatever]}}"
  elsif ...
end

The above would form a hash for all of the exact values you're searching for, avoiding SQL injection. 上面的代码将为您要搜索的所有确切值形成一个哈希,从而避免了SQL注入。 Then for such filters as prices you can just check whether the values are in correct format (numbers only) and only perform if so. 然后,对于价格之类的过滤器,您只需检查值是否采用正确的格式(仅数字),然后才执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM