Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

conditions hash to a LIKE conditions array (See related posts)

This method turns a conditions hash (like params[:some_object]) into a conditions array where each field is searched for via a LIKE, and can be used as the :conditions in any find or paginate call, for example:

{name => 'foo', location => 'bar'} becomes ["name LIKE ? and location LIKE ?", "%foo%", "%bar%"]

New to ruby, so no doubt there is a more concise (or even built in?) way to do this.

  def to_like_conditions( conditions )

    like_conditions = []
    key_count = conditions.size
    k = ""
    conditions.each_key do |key|
      k += "#{key} LIKE ?"
      if key_count > 1 
        k += " and "
      end
      key_count -= 1
    end
    like_conditions << k

    conditions.each_value do |value| 
      like_conditions << "%#{value}%"
    end

    like_conditions

  end



You need to create an account or log in to post comments to this site.


Click here to browse all 4857 code snippets

Related Posts