Sunspot Solr with Mongoid with id as String

12 May 2012

If you use a string `id` in Mongoid, then when the searching with Solr won't work properly.

When you try to obtain the results, Solr will throw an error `sunspot BSON::InvalidObjectId (illegal ObjectId format)`.

You need to fix the gem. There is a fork which fix it. You can find it here: https://github.com/jugyo/sunspot_mongoid/pull/10

However, it is not merged into the official branch. Let's not use it.

Let's go with the quick fix instead. You should create `sunspot_mongoid_fix.rbunder ``config/initializers```.

And please paste this content inside it:

module Sunspot module Mongoid class DataAccessor < Sunspot::Adapters::DataAccessor def load(id) if @clazz.using_object_ids? then @clazz.find(BSON::ObjectID.from_string(id)) rescue nil else @clazz.find(id) rescue nil end end def load_all(ids) Rails if @clazz.using_object_ids? then @clazz.where(:_id.in => ids.map { |id| BSON::ObjectId.from_string(id) }) else @clazz.where(:_id.in => ids) end end end end end

Give it a kudos