Search code examples
ruby-on-rails-3full-text-searchsunspotsunspot-railssunspot-solr

How to write searchable method for belongs_to assocication using sunspot_rails gem


I have two models. one is brand and another is product_detail. brands table has id and name fields and product_details table has fields id, name,price,discount and brand_id.

brand has many product_details and product_detail belongs to brand

brand.rb looks like:

class Brand < ActiveRecord::Base
    has_many :product_details
end

and product_details.rb looks like

class ProductDetail < ActiveRecord::Base
    belongs_to :Brand, :dependent=>:destroy
end

Am trying to do searching using sunspot rails. I want to search based on brand name and product name with the user entered text. To do this I have written searchable method like this:

class ProductDetail < ActiveRecord::Base
    belongs_to :brands, :dependent=>:destroy

     searchable do
      text :name
      text :brands do
        brands.map(&:name)
      end
    end
end

When i run rake sunspot:reindex

It is throwing an error undefined method map for nil class

If change the code like this

class ProductDetail < ActiveRecord::Base
    belongs_to :Brand, :dependent=>:destroy

     searchable do
      text :name
      text :Brand do
        brands.map(&:name)
      end
    end
end

It is throwing an error undefined method brands for product_detail class

Please help me how to do this.


Solution

  • It should be

    belongs_to :brand, :dependent=>:destroy
    

    but are you sure you want to delete the brand whenever you delete a product_detail associated with it?

    In any case, the searchable block should then be written as

    searchable do
      text :name
      text :brand do
        brand.name
      end
    end
    

    I hope, that helps.