狮身人面像和朋友搜索

时间:2013-02-25 01:48:02

标签: ruby-on-rails-3 sphinx has-many-through thinking-sphinx

我在Ruby on Rails上有一个关于Sphinx的高级问题:

说我想搜索的是我朋友写的文章。 模型结构将是:

User has_many users :through relationships
Article belongs_to User

我的问题是:我会在Sphinx上使用什么样的语法,以便用户搜索文章并只获取他朋友写的文章?我无法在网上找到这个,我想在实施我的解决方案之前掌握它的工作原理。

注意:我怀疑一个解决方案是拥有一个朋友ID数组,然后使用:condition:with => {:id => array_of_friendIDs}。但也许有一种更有效的方法呢?

1 个答案:

答案 0 :(得分:1)

你基本上是正确的 - 你将需要使用:with选项组装一组朋友ID并将其传递给搜索。但是,如何获取该列表与Sphinx并不特别相关。

friend_ids = current_user.users.pluck(:id)

@articles = Article.search(params['search_term'], :with => {:user_id => friend_ids})

使用.pluck将为您节省大量时间,否则将用于实例化一堆User对象 - 您只需要他们的ID。确保您已将user_id设置为Sphinx的属性(使用has user_id块中的define_index。)