我正在使用Thinking Sphinx为我的Rails应用程序上的搜索提供支持。
我知道指南明确说明you can't index model methods,但我想。具体来说,我有一个模型,其实例可以通过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
此搜索似乎工作得很好,但我在组合它们时遇到了麻烦,以便用户也可以使用继承的标签进行搜索。任何建议都非常感谢!
答案 0 :(得分: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