[英]ThinkingSphinx - Search through has_many association
我在两个模型( Idea
和Iteration
之间有关系。 每个想法可以有很多迭代。 模型看起来像这样;
# 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
我错过了什么吗?
实时索引和SQL支持的索引之间的区别之一是,对于SQL支持的索引,您引用索引定义中的关联和列,而对于实时索引,则引用方法。
尽管iterations
是一个idea
的实例方法,但是title
, description
和id
并不是iterations
返回的对象的方法。
解决此问题的最简单方法包括两部分。 首先,将实例方法添加到Idea中,以返回与迭代相关的字段和属性所需的数据:
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:regenerate
进行设置( ts:rebuild
和ts:index
对实时ts:index
没有意义)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.