4

当我有has_many, :through关联时,我正在尝试为模型建立索引,但没有显示任何结果。

class Business < ActiveRecord::Base
  include Tire::Model::Search
  include Tire::Model::Callbacks

  def self.search(params)
    tire.search(load: true) do
      query { string params[:q]} if params[:q].present?
    end
  end

  mapping do
    indexes :service_name
    indexes :service_description
    indexes :latitude
    indexes :longitude
    indexes :services do
      indexes :service
      indexes :description
    end
  end

  def to_indexed_json #returns json data that should index (the model that should be searched)
    to_json(methods: [:service_name, :service_description], include: { services: [:service, :description]})
  end

  def service_name
    services.map(&:service)
  end

  def service_description
    services.map(&:description)
  end

  has_many :professionals
  has_many :services, :through => :professionals

end

然后这是服务模型

class Service < ActiveRecord::Base
  attr_accessible :service, :user_id, :description
  belongs_to :professional
  belongs_to :servicable, polymorphic: true
end

我也使用这个重新索引:

rake environment tire:import CLASS=Business FORCE=true

我可以在 Business 中搜索项目,但是当我尝试在 Service 中搜索某些内容时,我得到一个空结果。

4

3 回答 3

5

在与映射作斗争之后,我创建了一个 gem 来使搜索更容易一些。https://github.com/ankane/searchkick

您可以使用该search_data方法来完成此操作:

class Business < ActiveRecord::Base
  searchkick

  def search_data
    {
      service_name: services.map(&:name),
      service_description: services.map(&:description)
    }
  end
end
于 2013-11-03T08:48:08.700 回答
3

我不相信有一种方法可以对与轮胎的关联进行映射。相反,您要做的是使用 :as 方法和 proc 定义易于搜索的字段。这样你也可以摆脱 to_indexed_json 方法(你实际上需要)

mapping do
  indexes :service_name
  indexes :service_description
  indexes :latitude
  indexes :longitude    
  indexes :service_name, type: 'string', :as => proc{service_name}
  indexes :service_description, type: 'string', :as => proc{service_description}
end
于 2013-11-01T15:16:13.203 回答
0

轮胎可以关联关联,我已经用它来索引 has_many 关联但还没有尝试过 has_many, :through 。尝试对对象进行索引?

mapping do
  indexes :service_name
  indexes :service_description
  indexes :latitude
  indexes :longitude
  indexes :services, type: 'object',
    properties: {
      service: {type: 'string'}
      description: {type: 'string'}
    }
end

此外,有一个触摸方法可能会很好:

class Service < ActiveRecord::Base
  attr_accessible :service, :user_id, :description
  belongs_to :professional, touch: true
  belongs_to :servicable, polymorphic: true
end

和 after_touch 回调来更新索引。

于 2013-11-08T00:25:25.747 回答