Searchkick 2嵌套'has_many'

时间:2016-05-02 04:10:17

标签: ruby-on-rails ruby elasticsearch searchkick

我有3节课。

Product, Command, CommandOption

我的搜索工作非常好。按产品搜索。 但我想通过CommandOption进行搜索并返回我的Product对象,该怎么做?

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

抱歉我的英文

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!

只需在模型Product中添加关系

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