In a Sunspot search, is it possible to use an attribute of the current model in the if statement of a sunspot scope?

UserFile.search do
  keywords searchstring
  order_by :last_edit_date
  with(:visibility,true) if some_method?(:user_id)
  paginate :page => page, :per_page => Pagination::FILES_PER_PAGE if page
end

In this example I want to call some_method? with complicated logic using the :user_id attribute of the UserFile model (this method will involve ActiveRecord queries).

What I am trying to to is limit search results such that files whose owners are strangers to the searcher (not friends with the searcher and not the searcher himself) do not show up if :visibility of UserFile is "1" (friends only) or "2" (private), and files whose owners are friends with the searcher do not show up if :visibility is "2" (private).

Is this possible with Solr/Sunspot or do I have to filter out the results once the search has finished? I don't want to resort to this since it will make pagination difficult.

有帮助吗?

解决方案

You cannot do this because the search block just passes in parameters to Solr to do the search. If you want to do this filtering purely in Solr (and have it actually be faster than using a database search), you will need to index the user id's who can see each record:

In your searchable block

integer :viewer_ids, references: User, multiple: true do
  some_method_that_returns_viewer_ids
end

You also need to make sure that saving whatever records changes these triggers a re-index.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top