I have a high-level question about Sphinx on Ruby on Rails:
Say I want to search are the articles written by my friends. The model structure would be:
User has_many users :through relationships
Article belongs_to User
My question is: what sort of syntax would I use on Sphinx so the user searches for articles and gets only the articles written by his friends? I am having trouble finding this online and I'd like to have a handle on how this would work before I implement my solution.
NOTE: I suspect one solution is to have an array of friend IDs and then use a :condition :with => {:id => array_of_friendIDs}. But maybe there is a more effective way of doing it?
You're basically correct - you're going to need to assemble an array of friend ids and pass it to the search, using the :with
option. How you fetch that list isn't particularly related to Sphinx, though.
friend_ids = current_user.users.pluck(:id)
@articles = Article.search(params['search_term'], :with => {:user_id => friend_ids})
Using .pluck
will save you a good bit of time that would otherwise be devoted to instantiating a bunch of User objects - you only need their ids. Make sure that you've set user_id
as an attribute for Sphinx (using has user_id
in the define_index
block).