Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

solr sunspot - searching belongs_to association

I have a fabrics model that belongs to multiple other tables.

class Fabric < ActiveRecord::Base
  validates :name, presence: true
  belongs_to :design
  belongs_to :composition
  belongs_to :collection
  belongs_to :style
  belongs_to :origin
  belongs_to :texture
  belongs_to :supplier
  has_and_belongs_to_many :colours

  searchable do
    text :name, :boost => 5 
    text :description
    text :composition do
      composition.name
   end
    text :collection do
      collection.name
    end
   text :style do
     style.name
   end
   text :origin do
     origin.name
   end
   text :texture do
     texture.name
  end
   text :supplier do
      supplier.name
  end
  end
  end

I have setup all of the reverse associations (Has_many) etc. However I do not seem to be able to get the fulltext search to query the name fields of all of these associated tables.

Any help would be greatly appreciated.

 @search = Fabric.search do
    fulltext params[:search]
  end
  @fabrics = @search.results

Ross

like image 209
RMcNairn Avatar asked Nov 29 '22 17:11

RMcNairn


2 Answers

You need to pass block inside your fulltext to specify which fields you want to search on.

@search = Fabric.search do
  fulltext params[:search] do
    fields(:collection, :style, :origin)
  end
  .....
end

Here is how you index in your searchable block. Solr thinks in terms of document. It doesn't care it's an association or not.

searchable do 
  text :collection do 
    collection.text 
  end
end

Then reindex.

Check this out for more detail https://github.com/sunspot/sunspot#full-text

https://github.com/sunspot/sunspot#setting-up-objects

like image 40
Chamnap Avatar answered Dec 06 '22 23:12

Chamnap


In case some association can be nil, do not forget to test for that otherwise you will get error while rebuilding index

text :collection do 
  collection.name if collection
end
like image 180
Anton Avatar answered Dec 07 '22 01:12

Anton