Topic: distinct select

I am using the Rails 3 Jquery Autocomplete plugin.  The problem with the plugin is it does not return distinct values.  I googled and found the following solution: http://stackoverflow.com/questions/4869 … -in-rails3

This solution suggested overriding the get_items function, which can be found at: https://github.com/crowdint/rails3-jque … 144d#L1R84

This works if you only are applying autocomplete for one field.  But what if you have autocomplete for multiple fields? For example, say you want to apply autocomplete to both title and author. How would you rewrite the following so it could serve both?

PostController
----------------------------------
autocomplete :post, :title, :full => true
autocomplete :post, :author, :full => true

def get_items(parameters)
     Post.select("distinct title").where(["title LIKE ?", "#{parameters[:term]}%"])
end

----------------------------------

Currently that only works for the title field. It does not work for the author field.

Re: distinct select

You control what is in parameters, correct?

parameters[:term]

You managed to get :term into the AJAX post, yes?

Why not stick a :search_field in there as well?

def get_items(parameters)
     Post.select("distinct #{parameters[:search_field]}").where(["#{parameters[:search_field]} LIKE ?", "#{parameters[:term]}%"])
end

Last edited by BradHodges (2011-02-10 13:52:16)

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: distinct select

Actually I don't control the request that's made - that logic is internal to the autocomplete gem.  But I found another (hack) way around my problem.  The autocomplete tries to handle things in a RESTful way, so it creates different routes for different form fields. E.g. /autocomplete_post_title?term=searchterm or /autocomplete_post_author?term=searchterm

So I can simply get the request url and see if it includes title or author, and then build the select statement based on the if condition.  A hack - but seems to do the trick.

def get_items(parameters)
if request.url.include? "title"
      Post.select("distinct title").where(["title LIKE ?", "#{parameters[:term]}%"])
elsif request.url.include? "author"
      Post.select("distinct author").where(["author LIKE ?", "#{parameters[:term]}%"])
end
end

Thanks for your help.

Re: distinct select

Cool

Here's a suggestion

if request.url.include? "_title_"

That way you could autocomplete on two fields:

title
title_orig

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: distinct select

Beauty.  Thanks, Brad!