1

我正在使用Thinking Sphinx来支持我的 Rails 应用程序上的搜索。

我知道该指南明确表示您不能索引模型方法,但我想这样做。具体来说,我有一个模型,其实例可以通过has_many_through关系通过acts_as_taggable_on_steroids. 重要的警告:模型也通过嵌套awesome_nested_set,我有通过嵌套继承的标签。

以下是我搜索继承标签的方式:

def inherited_tags
  retval = []
  cat = self
  while (cat = cat.parent)
    retval += cat.tags
  end
  retval.uniq
end

我可以使用以下方式通过显式(非继承)标签进行搜索:

define_index do
  indexes title
  indexes tags(:name)
end

此搜索似乎工作得很好,但我无法将它们组合起来以允许用户也使用继承的标签进行搜索。非常感谢任何建议!

4

1 回答 1

2

Sphinx 只能索引数据库中的数据,没有办法解决这个问题(有一个 XML 选项,但认为 sphinx 不支持它)。

您最好的选择是为您的模型添加一个缓存属性,该属性对用户不可见,但用于搜索。

尝试类似:

class Category < ActiveRecord::Base
   define_index do
     indexes title
     indexes cached_tags, :as => :tags
   end

   before_validate :cache_tags       

   def ancestors
     if self.parent
       self.parent.ancestors + [self.parent]
     else
       []
     end
   end

   def inherited_tags
     ancestors.map { |cat| cat.tags }.flatten.uniq
   end

   private

   def cache_tags
     self.cached_tags ||= inherited_tags.join(" ")
   end      
end
于 2010-08-03T00:00:49.820 回答