Search code examples
ruby-on-railsrubysolrcancansunspot

rails cancan sunspot search not working


I am using 'sunspot_solr', '~> 2.0.0' and 'cancan', '~> 1.6.8' gems in my rails app but I can't do a successful search using those two, say I have a resource called Photos and this is my search query

photos = Photos.accessible_by(current_ability).search do
 fulltext params[:query]
end.results

but the search happens on all photos not on those that belongs to current user, I believe current_user.photos and Photos.accessible_by(current_ability) are the same.

My ability.rb has this permissions

can :list, Photos
can [:read, :create, :update, :destroy], Photos, user_id: user.id

Any help would be much appreciated.


Solution

  • I don't think that the Sunspot search will filter based on a given scope, it just takes a model argument so it will search across all instances.

    You could do the search first and then filter the results but that would mess up paging if you are using Sunspot to do that.

    A better solution might be to index the user_id attribute in Solr so that you can do a search filtered by that as well as by the free text input. It isn't ideal because you would be duplicating authorisation logic.

    So in your model you would need:

    searchable do
      ...
      integer :user_id
    end
    

    You would need to rebuild the search index.

    And then include it in your search filter with something like:

    photos = Photos.search do
      fulltext params[:query]
      with(:user_id).equal_to(current_ability.user.id)
    end.results
    

    There is a discussion of a similar problem here.