Search code examples
ruby-on-railsrubyelasticsearchsearchkick

Searchkick 2 nesting 'has_many'


I have 3 classes.

Product, Command, CommandOption

I have search which work very nice. Search by product. But I want search by CommandOption and returned my Product object, how is do this?

class Product < ActiveRecord::Base


extend FriendlyId
  friendly_id :slug, use: :slugged



searchkick

  has_many :commands

  def search_data
    {
      name: name,

      #commands (has_many)
      command_captions: commands.map(&:caption).join(' '),
      command_numbers: commands.map(&:number).join(' '),

      #if I write here, then get error
      #command_option_caption: command_options.map(&:caption).join('')
    }
  end

end

class Command < ActiveRecord::Base
  belongs_to :product

  has_many :command_options
end

class CommandOption < ActiveRecord::Base
  belongs_to :command
end

Sorry for my English


Solution

  • I found solution!

    simply in model Product added relation

    class Product < ActiveRecord::Base
      searchkick
    
      has_many :commands
      has_many :command_options, through: :commands
    
    
      def search_data
        {
          name: name,
    
          #commands (has_many)
          command_captions: commands.map(&:caption).join(' '),
          command_numbers: commands.map(&:number).join(' '),
          #for commandoption model
          command_option_captions: command_options.map(&:caption).join(' ')
        }
      end
    
    end