Zyph Martin Design Studios Search


Zyph Martin Design Studios Recent Entries

THINGS I'M THANKFUL FOR

Posted on November 22 2012


BEST THING I'VE SEEN IN A LONG TIME.

Posted on April 11 2012


TELLING IT LIKE IT IS.

Posted on January 26 2012


COMING SOON TO A BROWSER NEAR YOU!

Posted on December 01 2011


SAY GOODBYE TO FLASH...

Posted on June 09 2011


VIEW ARCHIVES -->


JQUERY AUTOCOMPLETE AND MONGOID



Rails3jquery

When I updated our site to rails 3 I was using the standard rails autocomplete with prototype. Since I wanted to switch to jquery I did a google serach and I found this gem for rails 3 and jquery rails3-jquery-autocomplete but the syntax is different since I am using mongoid. So I modified it to work with mongoid changing the sql syntax to a mongo search syntax. Not sure if there is a big enough need to turn this into a gem and put it up on rubygems but you can find my fork on github if your interested in it here.

 

The original method for the plugin looked like this...

module ClassMethods
  def autocomplete(object, method, options = {})
    limit = options[:limit] || 10
    order = options[:order] || "#{method} ASC"

    define_method("autocomplete_#{object}_#{method}") do
      unless params[:term] && params[:term].empty?
        items = object.to_s.camelize.constantize.where(["LOWER(#{method}) LIKE ?", "#{(options[:full] ? '%' : '')}#{params[:term].downcase}%"]).limit(limit).order(order)
      else
        items = {}
      end

    render :json => json_for_autocomplete(items, (options[:display_value] ? options[:display_value] : method))
  end
end

def json_for_autocomplete(items, method)
  items.collect {|i| {"id" => i.id, "label" => i.send(method), "value" => i.send(method)}}
end

I changed removed the limit and order since we can just do that through the chaining of criteria that mongoid provides and I also change the json_for_autocomplete...

module ClassMethods
  def autocomplete(object, method, options = {})

    define_method("autocomplete_#{object}_#{method}") do
      unless params[:term] && params[:term].empty?
        items = Category.where("this.name.match(/#{params[:term]}/i)").limit(10).asc(method)
      else
        items = {}
      end

    render :json => json_for_autocomplete(items, method)
  end
end

def json_for_autocomplete(items, method)
  items.collect {|i| {"id" => "#{i.id}", "label" => "#{i.name}", "value" => "#{i.name}"}}
end


Back To Blog - Posted on September 09 2010 by Brandon Martin




blog comments powered by Disqus