views:

101

answers:

2

I'm using acts_as_solr for searching in a project. Unfortunately, the index doesn't seem to be updated for the associated models when a model is saved.

Example:

I have three models:

class Merchant < ActiveRecord::Base
  acts_as_solr :fields => [:name, :domain, :description], :include => [:coupons, :tags]
  ...
end

class Coupon < ActiveRecord::Base
  acts_as_solr :fields => [:store_name, :url, :code, :description]
  ...
end

class Tag < ActiveRecord::Base
  acts_as_solr :fields => [:name]
  ...
end

I use the following line to perform a search:

Merchant.paginate_by_solr(params[:q], :per_page => PER_PAGE, :page => [(params[:page] || 1).to_i, 1].max)

For some reason though, after I add a coupon that contains the word 'shoes' in the description, a query for 'shoes' doesn't return the merchant associated with the coupon. The association all work and if I run rake solr:reindex, the search then returns the new coupon.

Do I need to update the index for Merchant each time a new coupon is created? Do I have to update the index for the whole class or can I just update the associated merchant?

Shouldn't this be done automatically?

Thanks for any input.

A: 

I use Sunspot so there will likely be differences, but I've had to setup callbacks on associated models to re-index the parent record. I'm guessing you'll have to do the same thing.

jonnii
Yep, as you can see from above, that's what I ended up having to do. Thanks.
Trey Bean
A: 

Okay, it turns out a couple things were going on.

On the coupon model, I put in an after_save callback to update the solr doc for the associated merchant:

def update_merchant_solr
  merchant.solr_save
end

The tag issue was due to the order of the after_save callbacks on acts_as_solr and is_taggable. The merchant after_save that solr inserts occurred before the is_taggable callback, thus, when the merchant solr callback was called to update its doc, the tags hadn't been associated with it yet. Switching the order worked:

class Merchant < ActiveRecord::Base
  is_taggable :tags
  acts_as_solr :fields => [:name, :domain, :description], :include => [:coupons, :tags]
  ...
end
Trey Bean
In my app I've used `model.touch`.
jonnii