Limit autocomplete results based on model relations

Imagine we have a Product and a Brand models linked by a 'has_many' relation:

    class Brand < ActiveRecord::Base
      has_many :products
    end
    
    class Product < ActiveRecord::Base
      belongs_to :brand
    end

In the show view of the BrandsController you have a search_field used to find a product of the current brand object.
You want this field to do autocompletion on the name attribute of the product model. 
You don't want to query on all the products existing in the database but only to the products that belongs to the current brand object.

To do that you first need to add the autocomplete action to your brand controller:

    class BrandsController < Admin::BaseController
      autocomplete :product, :name
    end

In your routes file you'll not add a "collection" but a "member" entry to the brands resources:

    resources :brands do
      get :autocomplete_product_name, :on => :member
    end

As this is a member route, the "autocomplete_product_name" method of your BrandController will get a params[:id].
The search will retreive the brand object thanks to this id and will only search for matching products within: brand.products

Take a look at the README file for more informations about this feature and the new options you can pass to the 'autocomplete' statement in the controller.

I hope that this may be useful.

Kind regards,

Julien (XAOP)