太阳黑子/ Solr/Rails:模型关联未在指数中更新

lan*_*ide 5 solr sunspot ruby-on-rails-3

我的应用程序中有一个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
Run Code Online (Sandbox Code Playgroud)

然后我有一个搜索模型来存储/更新搜索.因此,搜索模型也与活动有关联.然后我执行我的搜索:

@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
Run Code Online (Sandbox Code Playgroud)

现在这一切都很有效.问题是,如果我更改与fieldnote关联的活动,搜索结果不会更改,因为它会显示该fieldnote的索引不会更改.当我定义可搜索索引时,我的印象是:auto_index => true和:auto_remove => true标志将跟踪新关联(或删除的关联),但似乎并非如此.我该如何解决?

Nic*_*zny 9

你是正确的,:auto_index并且:auto_remove并不适用于关联的对象,就在searchable他们指定的对象.

非规范化时,您应该after_save在关联对象上使用挂钩,以在必要时触发重新索引.在这种情况下,你要更改Activity模型,并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
Run Code Online (Sandbox Code Playgroud)