Search code examples
ruby-on-rails-3.2sunspot

sunspot - indexing has_one association


I have the following 'submission' model.

class Submission < ActiveRecord::Base
  self.table_name = "SUBMISSION"
  self.primary_key = "SUB_ID"

  has_one  :publication,             :foreign_key => "PUB_SUBMISSION_FK", :dependent => :destroy
  has_one  :refpublication,          :through => :publication

  belongs_to :submitter, :class_name => "Person", :foreign_key => "SUB_SUBMITTER_FK"


  #***************************************************************************************
  #Solr searchable attributes
  #***************************************************************************************

searchable do

  text :publication_PUB_REF_ID do
    publication.PUB_REF_ID
  end

  text :submitter_PER_NAME do
    submitter.PER_NAME
  end

  text :SUB_OID, :boost => 5
  text :SUB_ASSAY_TYPE

end

end #end of submission class

When I run rake sunspot:reindex, I get

rake aborted! undefined method `PUB_REF_ID' for nil:NilClass.

I can't see what is wrong with the code above. `PUB_REF_ID' is a field in the 'publications' table Is there something wrong with the way I am indexing 'has_one' association?

Your help is very much appreciated :)


Solution

  • Found the solution :)

    Not all submissions had rows in my 'publications' table.

    Here's the solution I used:

    Instead of:

     text :publication_PUB_REF_ID do
        publication.PUB_REF_ID
      end
    

    I use:

     text :publication_PUB_REF_ID do
          publication.nil?? '' : (publication.PUB_REF_ID.nil?? '' : publication.PUB_REF_ID)
        end
    

    Hope this could be of help to someone else :)