ThinkingSphinx - 搜索has_many关联

时间:2015-03-11 20:32:57

标签: ruby-on-rails ruby sphinx thinking-sphinx

我有两个模型IdeaIteration之间的关系。每个想法都可以有很多次迭代。模型看起来像这样;

# idea.rb
has_many :iterations, dependent: :destroy

# I also use with: :real_time 
after_save ThinkingSphinx::RealTime.callback_for(:idea)

# iteration.rb
belongs_to :idea
after_save ThinkingSphinx::RealTime.callback_for(:idea, [:idea])

Idea的索引如下所示:

ThinkingSphinx::Index.define :idea, :with => :real_time do
  [...]
  indexes iterations.title, as: :iteration_titles
  indexes iterations.description, as: :iteration_descriptions
  has iterations.id, :as => :iteration_ids, type: :integer
  [...]
end

我这样搜索:

@ideas = @user.ideas.search  ThinkingSphinx::Query.escape(params[:search]),
  :with => {:team_id => @teams.collect(&:id)},
  :page     => params[:page],
  :per_page => 10,
  :order    => 'created_at DESC'

目前,搜索Iteration标题或说明会返回 0 点击。我已经表演了:

rake ts:rebuild
rake ts:regenerate
rake ts:index

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

实时索引和SQL支持的索引之间的区别之一是,对于SQL支持的索引,您引用索引定义中的关联和列,但是使用实时索引,您可以引用方法。

虽然iterationsidea中的实例方法,但titledescriptionid不是{{1}返回的对象上的方法}}

最简单的解决方法有两部分。首先,向Idea添加实例方法,返回与迭代相关的字段和属性所需的数据:

iterations

然后在索引定义中使用这些方法:

def iteration_titles
  iterations.collect(&:title).join(' ')
end

def iteration_descriptions
  iterations.collect(&:description).join(' ')
end

def iteration_ids
  iterations.collect &:id
end

然后,运行indexes iteration_titles, iteration_descriptions has iteration_ids, :type => :integer, :multi => true 以完成所有设置(rake ts:regeneratets:rebuild对实时索引毫无意义。)

相关问题