使用OR和AND搜索多个列以应用过滤器

时间:2016-09-25 20:26:02

标签: ruby-on-rails sqlite search conditional-statements where

我正在开发一款应用。我试图植入一个搜索系统。方法很简单。在家里,我搜索3列“名称”或“nomdep”或“nomregion”的查询。在此之后,我想用AND运算符过滤params。

如果我只使用一列植入搜索,例如“NAME”,那么我可以应用过滤器。但是,如果我想用多个OR植入这个,我不能应用过滤器。我认为OR运算符是问题所在。但是我肯定不知道要解决这个问题......

你能帮帮我吗?感谢

camping.rb

has_many :caracteristiquetests, :foreign_key => :camping_id
has_many :situations, :foreign_key => :camping_id

    def self.searchi(query, handicap, animaux, television, plage, etang, lac)
       return scoped unless query.present?
       left_outer_joins(:caracteristiquetests, :situations).where(['nomdep LIKE ? OR name LIKE ? OR nomregion LIKE ? AND handicap LIKE ? AND animaux LIKE ? AND television LIKE ? AND plage LIKE ? AND etang LIKE ? AND lac LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%", "%#{handicap}%", "%#{animaux}%", "%#{television}%", "%#{plage}%", "%#{etang}%", "%#{lac}%"])
    end

camping_controller.rb

      def resultnohome
        if params[:query].blank?
          redirect_to action: :index and return
        else
          @campings = Camping.searchi(params[:query], params[:handicap], params[:animaux], params[:television], params[:plage], params[:etang], params[:lac])
        end
end

caracteristiquetest.rb

belongs_to :camping

situation.rb

belongs_to :camping

修改

我编辑了我的模型以添加“()”

camping.rb

def self.searchi(query, handicap, animaux, television, plage, etang, lac)
   return scoped unless query.present?
   left_outer_joins(:caracteristiquetests, :situations).where(['(nomdep LIKE ? OR name LIKE ? OR nomregion LIKE ?) AND handicap LIKE ? AND animaux LIKE ? AND television LIKE ? AND plage LIKE ? AND etang LIKE ? AND lac LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%", "%#{handicap}%", "%#{animaux}%", "%#{television}%", "%#{plage}%", "%#{etang}%", "%#{lac}%"])
end

Unfornutualy,我得到意想不到的结果:只显示一个结果,第一个匹配如“短路评估”。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

只需在login_2条件周围使用括号,or条件的结果就会与or条件结合使用。

and

或者,您可以将其拆分为单独的left_outer_joins(:caracteristiquetests, :situations).where(['(nomdep LIKE ? OR name LIKE ? OR nomregion LIKE ?) AND handicap LIKE ? AND animaux LIKE ? AND television LIKE ? AND plage LIKE ? AND etang LIKE ? AND lac LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%", "%#{handicap}%", "%#{animaux}%", "%#{television}%", "%#{plage}%", "%#{etang}%", "%#{lac}%"]) 语句,这些语句将在您检索结果时组合成一个SQL调用。这样更容易阅读和维护,并且在没有提供值的情况下也不会进行任何调用。

where