我的应用程序中有一个 Fieldnote 模型,它通过名为 :fieldnote_activities 的表附加了_many :activities。然后我这样定义一个可搜索索引:
searchable :auto_index => true, :auto_remove => true do
integer :id
integer :user_id, :references => User
integer :activity_ids, :multiple => true do
activities.map(&:id)
end
text :observations
end
然后我有一个搜索模型来存储/更新搜索。因此,搜索模型也与活动有其自身的关联。然后我像这样执行搜索:
@search = Search.find(params[:id])
@query = Fieldnote.search do |query|
query.keywords @search.terms
if @search.activities.map(&:id).empty? == false
query.with :activity_ids, @search.activities.map(&:id)
end
end
@fieldnotes = @query.results
现在这一切都很好。问题是,如果我更改与字段注释关联的活动,搜索结果不会更改,因为该字段注释的索引似乎不会更改。我的印象是,当我定义可搜索索引时, :auto_index => true 和 :auto_remove => true 标志将跟踪新关联(或删除的关联),但事实似乎并非如此。我该如何解决?
你说得对:auto_index
and :auto_remove
不适用于关联对象,仅适用于searchable
它们被指定的对象。
当反规范化时,你应该使用after_save
挂钩关联对象以在必要时触发重新索引。在这种情况下,您希望更改Activity
model and the FieldnoteActivity
加入模型以触发其关联的重新索引Fieldnote
保存或销毁时的对象。
class Fieldnote
has_many :fieldnote_activities
has_many :activities, :through => :fieldnote_activities
searchable do
# index denormalized data from activities
end
end
class FieldnoteActivity
has_many :fieldnotes
has_many :activities
after_save :reindex_fieldnotes
before_destroy :reindex_fieldnotes
def reindex_fieldnotes
Sunspot.index(fieldnotes)
end
end
class Activity
has_many :fieldnote_activities
has_many :fieldnotes, :through => :fieldnote_activities
after_save :reindex_fieldnotes
before_destroy :reindex_fieldnotes
def reindex_fieldnotes
Sunspot.index(fieldnotes)
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)