如何向此Find数组添加LIKE条件?

时间:2014-01-14 05:45:58

标签: ruby-on-rails sql-injection ruby-on-rails-2

提前感谢您的帮助。我正在按照我在此处找到的示例(Rails Find when some params will be blank)并尝试为搜索表单组合一系列条件。这适用于Rails 2.3遗留应用程序。以下适用于我,但我不知道如何做除“=”以外的任何事情。例如,如何使programs_offered_category条件成为LIKE语句?我试着做了

    majorcategories = params[:majorcategories]

在条件声明之上并添加

    conditions['programs_offered_category LIKE ?', "%#{majorcategories}%"]

但我得到“错误的参数数量(2对1)”。另外,如何在此设置中执行大于和小于标记的操作?谢谢!

search_controller.rb

    conditions = {}
    conditions[:city] = params[:city] unless params[:city].blank?
    conditions[:state] = params[:state] unless params[:state].blank?
    conditions[:geo_region] = params[:geo_region] unless params[:geo_region].blank?
    conditions[:size_category] = params[:size_category] unless params[:size_category].blank?
    conditions[:programs_offered_category] = params[:majorcategories]

    @location_matches = Masterlocation.find(:all, :conditions => conditions, :order => 'nickname ASC').paginate(:page => params[:page], :per_page => 20)

1 个答案:

答案 0 :(得分:0)

我建议使用正则表达式如下

conditions['programs_offered_category'].map {|k,v| (k =~ /majorcategories/) ? v : nil}

如果存在多个匹配,则返回结果数组,否则返回单个值