Sash
Sash

Reputation: 4598

Rails simple filtering using LIKE

I'm looking for a simple way to build up a filter query using given column/value hash. All of the values should be used in LIKE queries. I can build up the query and the parameters in arrays and pass it to where, like this:

  def self.filter(filters=nil)

    if filters.nil? || filters.empty?
     return all
    end

    query = []
    value_array = []
    filters.each do |key, value|
      query << "#{key} LIKE ?"
      value_array << "%#{value}%"
    end

    where([query.join(' AND ')] + value_array)

  end

But I was wondering if there is a better way of doing this either built into Rails (using version 4) or if there is a super simple gem that can easily accept a has and turn into a LIKE filter?

Upvotes: 0

Views: 613

Answers (1)

Kostas
Kostas

Reputation: 135

a nice way to play nice with hashes in queries is to make use of the Hash#slice method and scopes:

...
filtering_params(params).each do |key, value|
   @products = @products.public_send(key, value) if value.present?
end

def filtering_params(params)
 params.slice(:status, :location, :starts_with)
end

class Product < ActiveRecord::Base
   scope :status, -> (status) { where status: status }
   scope :location, -> (location_id) { where location_id: location_id }
   scope :starts_with, -> (name) { where("name like ?", "#{name}%")}
end

Taken from here. After all you might need to restrict you logic to some specific queries in your DSL.

Upvotes: 1

Related Questions