I have a Rails 4 app and I am trying to search my Task model using the Searchkick gem. But, I only want the search results to include Tasks that the current user has a certain Rolify role for. Basically, the user can't search for other user's Tasks.
The Rolify gem has a method for getting the Tasks that the current user has a certain role for.
Task.with_role(:viewer, current_user) #=> Tasks where the current user has a viewer role.
I cannot figure out how to filter the Searchkick results to only search the Tasks returned in the code above. I want to do something like this,
Task.with_role(:viewer, current_user).search("foo") #=> Returns all Tasks that match foo
But, it includes all Tasks that match foo instead of just the current user's Tasks that match foo. I know that there is a UsersRoles table that Rolify uses to relate the users and roles, but I don't know how to relate that to the Task model's roles.
Is it possible to search the Task model's roles for a certain role that belongs to the current user all in a Searchkick query?
Try using Searchkick/elaticsearch-rails's records
feature to do this.
Task.search("foo").records.with_role(:viewer, current_user)
records
converts the results into essentially a where(id: [ids, matching, the, elasticsearch, query])
scope that you can add other queries onto.