Searchlight and CanCan

I’m currently working on a client project where site adminstrators use the same UI that site users do, so there are permissions checks in the views and controllers to ensure the current user has the right to do or see certain things. CanCan provides the access control, which takes care of most of the issues with a simple can? check or load_and_authorize_resource.

In one case I wanted to provide search on a list of items (the index action) to admins so they could search through all items in the database, but users should be able to only search on their own items. I’m using Searchlight (highly recommended) for search, which returns results as an ActiveRecord::Relation, so it’s easily chainable via CanCan, like so:

class InvoicesController < ApplicationController
  def index
    @search = InvoiceSearch.new(params[:search])
    @invoices = @search.results.accessible_by(current_ability, :index)
  end
end

Searchlight is also smart enough to return all results if there no search params provided, so this also works as a typical index action that lists all items the user can see. If you’re curious about the @search instance variable, that is used in the search form in the index view.

So, if you need search with access control, use Searchlight and CanCan… they are a great combo!

Comments