Rails gem rails3-jquery-autocomplete how to scope by user

In posts_controller:

 def get_autocomplete_items(parameters)
    items = super(parameters)
    items = items.where(:user_id => current_user.id)
  end

I'm first calling the original get_autocomplete_items method, and then filtering out the results by current_user.id.

This question helped: Rails 3: alias_method_chain still used?


I had a similar problem I solved thanks to the answers above.

My autocomplete also worked against a User model, but I needed to restrict the results to the user's institution (Institution has many :users). My controller creates an @institution instance variable that is accessed in the view.

Although the get_autocomplete_items method cannot directly access the instance variable, I found that the data CAN be passed to autocomplete as a parameter (note: I use the simple_forms gem, so the input call looks a little different than the standard rails syntax).

In my view:

<%= f.input :email,  :url => autocomplete_user_email_institutions_path(:institution_id=>@institution.id.to_s), :as => :autocomplete %>

In my controller:

  autocomplete :user, :email, :extra_data => [:first_name, :last_name]

  def get_autocomplete_items(parameters)
    super(parameters).where(:institution_id => params[:institution_id])
  end

My autocomplete list is now scoped to just the users who work for a particular institution.


deb's answer works for me. The code can be cleaned up a bit:

def get_autocomplete_items(parameters)
  super(parameters).where(:user_id => current_user.id)
end