[英]ThinkingSphinx - Search through has_many association
I have a relationship between two models, Idea
and Iteration
. 我在两个模型(
Idea
和Iteration
之间有关系。 Each idea can have many iterations. 每个想法可以有很多迭代。 The models looks like this;
模型看起来像这样;
# 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])
My indexes for Idea
looks like this: 我的
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
And I search like this: 我这样搜索:
@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'
Currently, searching for either Iteration
title or description returns 0 hits. 当前,搜索
Iteration
标题或描述将返回0个匹配。 And I have performed: 我执行了:
rake ts:rebuild
rake ts:regenerate
rake ts:index
Have I missed something? 我错过了什么吗?
One of the differences between real-time indices and SQL-backed indices is that with SQL-backed indices, you refer to associations and columns in your index definition, but with real-time indices, you refer to methods. 实时索引和SQL支持的索引之间的区别之一是,对于SQL支持的索引,您引用索引定义中的关联和列,而对于实时索引,则引用方法。
And while iterations
is an instance method within an idea
, title
, description
and id
are not methods on the object returned by iterations
. 尽管
iterations
是一个idea
的实例方法,但是title
, description
和id
并不是iterations
返回的对象的方法。
The easiest way to work through this has two parts. 解决此问题的最简单方法包括两部分。 Firstly, add instance methods to Idea that return the data you want for the iteration-related fields and attributes:
首先,将实例方法添加到Idea中,以返回与迭代相关的字段和属性所需的数据:
def iteration_titles
iterations.collect(&:title).join(' ')
end
def iteration_descriptions
iterations.collect(&:description).join(' ')
end
def iteration_ids
iterations.collect &:id
end
And then use those methods in your index definition: 然后在索引定义中使用这些方法:
indexes iteration_titles, iteration_descriptions
has iteration_ids, :type => :integer, :multi => true
And then, run rake ts:regenerate
to get it all set up ( ts:rebuild
and ts:index
have no meaning for real-time indices). 然后,运行
rake ts:regenerate
进行设置( ts:rebuild
和ts:index
对实时ts:index
没有意义)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.