Ruby on Rails - search in database based on a query

前端 未结 4 906
灰色年华
灰色年华 2021-01-26 05:54

I have a simple form, where I set up a query that I want to browse, for example panasonic viera. This is on how I search the term in database:

P         


        
4条回答
  •  生来不讨喜
    2021-01-26 06:30

    How about via ARel

    def self.search(query)
      words      = query.split(/\s+/)
      table      = self.arel_table
      predicates = []
    
      words.each do |word|
        predicates << table[:name].matches("%#{word}%")
      end
    
      if predicates.size > 1
        first = predicates.shift
        conditions = Arel::Nodes::Grouping.new(predicates.inject(first) {|memo, expr| Arel::Nodes::Or.new(memo, expr)})
      else
        conditions = predicates.first
      end
    
      where(conditions).to_a
    end
    

提交回复
热议问题