Reputation: 112
I've been stuck for a few days on this. I have been using railscasts #102 revised as a template.
Ultimately I plan to have a search box in the top menu bar using ajax to query the name field of two seperate models which uses jquery-ui autocomplete and when clicked link directly to the show action for the selected search result.
But I'm not even there yet, right now I'm just trying to get the autocomplete to work with a single model. Here's what I have:
-Opportunity model, searching off the NAME attribute
-Search Controller
def index
@opportunities = Opportunity.order(:name).where("name like ?", "#{params[:term]}")
render json: @opportunities.map(&:name)
end
Search.js.coffee
jQuery ->
$('#search').autocomplete
source: $('#search').data('autocomplete-source')
Search view (/app/views/layouts/application.html.erb:
<%= text_field_tag 'search', nil, :class => 'search-query ui-autocomplete-input', :placeholder => 'Search', data: {autocomplete_source: search_path} %>
When I run this code, as I type letters into the search box (lets assume I type the letter B), I get:
Started GET "/search?term=b" for 127.0.0.1 at 2012-03-01 15:17:40 -0800
Processing by SearchController#index as JSON
Parameters: {"term"=>"b"}
Opportunity Load (0.3ms) SELECT "opportunities".* FROM "opportunities" WHERE (name like 'b') ORDER BY opportunities.name, name
Completed 200 OK in 1ms (Views: 0.1ms | ActiveRecord: 0.3ms)
What I would now expect to happen is the autocomplete would use the B, select all Names in the model, and drop them down in the autocomplete, instead, I get nothing, nothing happens.
If I adjust my view with the following:
<%= text_field_tag 'search', nil, :class => 'search-query ui-autocomplete-input', :placeholder => 'Search', data: {autocomplete_source: @opportunities.map(&:name)} %>
Then the autocomplete will work, but each page with the search bar will load all search terms to the client side. With a potential of thousands of names I don't want to load all that data, I want the ajax call to be made live against the database and adjust the view accordingly.
I'm new with rails so I'm sure I am making a dumb mistake here. Any help would be so much appreciated.
Thank you
Upvotes: 2
Views: 3015
Reputation: 864
It appears that you are not putting any wild cards in your like statement
@opportunities = Opportunity.order(:name).where("name like ?", "#{params[:term]}")
should be
@opportunities = Opportunity.order(:name).where("name like ?", "%#{params[:term]}%")
This is related to another question: How to search for a text with Active Record in Ruby on Rails 3?
Upvotes: 1