我的应用程序中有一个Fieldnote模型,其中has_many:通过名为fieldnote_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
现在这一切都很有效。问题是,如果我更改与fieldnote关联的活动,搜索结果不会更改,因为它会显示该fieldnote的索引不会更改。我的印象是:auto_index => true和:auto_remove =>当我定义可搜索索引时,真正的标志将跟踪新的关联(或删除的关联),但似乎并非如此。我该如何解决这个问题?
答案 0 :(得分:9)
你是对的,:auto_index
和:auto_remove
不适用于关联对象,只适用于指定它们的searchable
对象。
当进行非规范化时,您应该在关联对象上使用after_save
挂钩,以在必要时触发重新索引。在这种情况下,您希望更改Activity
模型和 FieldnoteActivity
联接模型,以便在保存或销毁时触发其关联的Fieldnote
对象的重新索引。< / p>
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