【问题标题】:Searchkick 2 nesting 'has_many'Searchkick 2 嵌套'has_many'
【发布时间】:2016-05-02 14:45:33
【问题描述】:

我有 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

对不起我的英语

【问题讨论】:

    标签: ruby-on-rails ruby elasticsearch searchkick


    【解决方案1】:

    我找到了解决办法!

    只需在模型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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 2019-08-21
      • 2012-03-10
      • 1970-01-01
      • 2015-09-11
      • 2019-05-21
      相关资源
      最近更新 更多