Reputation: 3168
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.
Upvotes: 1
Views: 285
Reputation: 5528
Even if I consider Steve answer correct you will have two different places in which you define permissions for the photos, and this is not nice because we are actually using cancan for that.
I would prefer using something like:
photos = Photo.search do
fulltext params[:query]
with(:id, Photo.accessible_by(current_ability).pluck(:id))
end.results
so you do not have to duplicate the logic for permissions.
btw: why Photos
instead of Photo
?
Upvotes: 0
Reputation: 15736
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.
Upvotes: 1