Indexing Associated Models with Solr Sunspot - Rails

196 Views Asked by At

I have 4 models. Product, ProductMachines (joins table with part number attribute), Machine and Brand. Essentially, the Product table has and belongs to many Machines. A machine belongs to a Brand. This structure allows me to associate a product with different machines for different brands while specifying a unique part number for each machine on the joins table for Products and Machines. I am trying to search the Product table along with all of the associated data mentioned below. However, I am having problems indexing all of the associated data correctly.

class Brand < ApplicationRecord
    has_many :machines
end 

class Machine < ApplicationRecord
    belongs_to :brand
    has_many :product_machines, dependent: :destroy
    has_many :products, through: :product_machines
end

class ProductMachines < ApplicationRecord
    belongs_to :machine
    belongs_to :product
end

class Product < ApplicationRecord
    has_many :product_machines, dependent: :destroy
    has_many :machines, through: :product_machines

    searchable do
        text :name
        text :machines do
            machine.name
            #how would I index the brand name (parent of machine)
            #how would I also index the part number field that is on the ProductMachines table?
        end
    end
end

I get the idea that I would either need to implement a join or add multiple text fields for indexes like below:

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

end

However, using this implementation I get the idea that if I filtered the brand with something like with(:brand, "my brand") then the filter wouldn't exclude machine names that are explicitly associated with A DIFFERENT brand. I however don't know how to confirm this. That's where I need help. I would implement and test a join across all of my models, but I can only find documentation for joining two directly related models; not models with a has_many :through relationship.

Thanks in advance.

1

There are 1 best solutions below

0
user3309314 On

I worked with Solr using Sunspot gem a while ago. As I remember there is an multiple option. So you can try index your data as an array like that:

searchable do
  string(:brands, multiple: true) { brands.map(&:name }
end

and then search like with(brands, ['foo', 'bar'])

PS take a look at ElasticSearch