【问题标题】:How to index model association in Tire(retire)如何在轮胎(退休)中索引模型关联
【发布时间】:2014-01-17 23:18:47
【问题描述】:

您好,我在一个 rails 项目中使用 retire 和 elasticsearch 来索引我的用户和一个额外的模型 special_codes。我的目标是为我的用户模型添加一个索引,这样当我搜索用户时,新索引(特殊代码)将提供命中。

class User < ActiveRecord::Base
  include Tire::Model::Search
  include Tire::Model::Callbacks
  has_one :specialcode

  after_create :generate_specialcode

  mapping do
    indexes :email, :type => 'string'
    indexes :specialcode do 
      indexes :code, :type => 'string'
    end
  end

  def to_indexed_json
    to_json( include: { specialcode: {only: [:code]} })
  end

  private

  def generate_specialcode
    Specialcode.create(code: 'derp', user_id: self.id)
    self.tire.update_index #not really needed(see after_save), just here for example.
  end
end

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

  belongs_to :user

  after_save :update_user_index

  private

  def update_user_index
    self.user.tire.update_index
  end
end

我希望看到User.search('derp') 带回用户点击,因为我已将特殊代码与用户一起编入索引。我已经尝试了很多映射和更新索引而没有任何命中。上面的示例有望为工作提供一个基础。谢谢

更新

我在布鲁斯的帮助下找到了解决方案。我在上面的代码中添加了mappingto_indexed_jsonupdate_user_index

【问题讨论】:

    标签: ruby-on-rails elasticsearch tire


    【解决方案1】:

    我想你已经在用户模型中有 to_indexed_json 和映射?尝试使用 after_touch 回调来更新用户中的索引。

    【讨论】:

    • 布鲁斯感谢您的回复。它让脑汁再次流动。我的 to_indexed_json 不正确。我在thread 中偶然发现了我的错误。我将更新上面的代码以反映修复。
    猜你喜欢
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2012-06-30
    • 2014-01-03
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多