Applying permission model to search results
Enterprise applications usually have a role base access control (RBAC). The search results as well as the auto-completer suggestions must conform to the access control model. The recommended way to control the search results, using scoped_search, is chaining scopes. The scoped_search is a named scope (scope in rails 3), this means that it can be chained with other scopes in a natural way.
For example:
scope :my_hosts, lambda {
where("owner_id = ?", User.current.id)
}
Host.my_hosts.search_for(query)
In the above code :my_hosts is the RBAC scope (defined in lines 1 to 3). In line 4 the search is chained to the RBAC scope.
For the auto-completer there is a new way of filtering the results in a similar way. In the Model we can define a scope called :compelter_scope , this scope should accept an options hash. The options hash is a way to pass parameters from the controller, such as the current user.
For example:
Model code:
scope :completer_scope, lambda { |options|
where('owner_id = ?', options[:owner_id])
}
Controller code:
def auto_complete_search
@items = Host.complete_for(params[:search], {:owner_id => User.current.id})
render :json => @items
end
To read more about named scopes, here is a link to a detailed post on the subject: Skinny on scopes
Nice!