加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:Elasticsearch:通过关联映射

发布时间:2020-12-17 03:40:41 所属栏目:百科 来源:网络整理
导读:当我有一个has_many时,我正试图索引模型:通过关联,但没有显示任何结果. 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]}
当我有一个has_many时,我正试图索引模型:通过关联,但没有显示任何结果.

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中搜索某些内容时,我得到一个空的结果.

解决方法

在与映射挣扎之后,我创建了一个宝石,使搜索更容易一些. 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读