title: Indexing Associated Models with Solr Sunspot - Rails
body: <p>I have 4 models. <code>Product</code>, <code>ProductMachines</code> (joins table with part number attribute), <code>Machine</code> and <code>Brand</code>. Essentially, the <code>Product</code> table has and belongs to many <code>Machines</code>. A machine belongs to a <code>Brand</code>. 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 <code>Products</code> and <code>Machines</code>. I am trying to search the <code>Product</code> table along with all of the associated data mentioned below. However, I am having problems indexing all of the associated data correctly.  </p>
  
  <pre><code>class Brand &lt; ApplicationRecord
      has_many :machines
  end 
  
  class Machine &lt; ApplicationRecord
      belongs_to :brand
      has_many :product_machines, dependent: :destroy
      has_many :products, through: :product_machines
  end
  
  class ProductMachines &lt; ApplicationRecord
      belongs_to :machine
      belongs_to :product
  end
  
  class Product &lt; 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
  </code></pre>
  
  <p>I get the idea that I would either need to implement a join or add multiple text fields for indexes like below:</p>
  
  <pre><code>searchable do
      text :name
      text :machines do
           machines.name
      end
      text :product_machines do
           product_machines.map(&amp;:part_number)
      end
      text :brands do
          brands.map(&amp;:name) 
      end
  
  end
  </code></pre>
  
  <p>However, using this implementation I get the idea that if I filtered the brand with something like <code>with(:brand, "my brand")</code> 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. </p>
  
  <p>Thanks in advance.</p>