Search code examples
ruby-on-railsautocompleteruby-on-rails-plugins

Rails auto_complete with a subset of objects


Here are my models:

class User < ActiveRecord::Base
  has_many    :artists
end

class Artist < ActiveRecord::Base
  belongs_to    :user
end

I am trying to implement an auto_complete text field where artist names are auto completed:

<%= text_field_with_auto_complete :artist, :name, { :size => 60}, {:skip_style => false, :tokens => ','} %>

This works but autocompletes over all Artists defined in the database. What do I need to do to limit the returned auto_complete results to only the Artists belonging to the logged in User?

Thanks a lot!


Solution

  • Presumably you've got something like this in your controller:

    def auto_complete_for_artist_name
      @artists = Artist.find(:all, 
       :conditions => "name LIKE (?)", params[:artist][:name])
    end
    

    You'll need to change that to either add the current user to the conditions or use the association like this:

    def auto_complete_for_artist_name
      # assumes you have a 'current_user' method 
      # which returns the current logged in user
      @artists = current_user.artists.find(:all, 
         :conditions => "name LIKE (?)", params[:artist][:name])
    end
    

    That will give you just the artists belonging to the current user.