嗨,我在Rails项目中使用retire和elasticsearch来索引我的用户和其他模型special_codes。我的目标是向我的用户模型添加索引,以便在我搜索用户时,新索引(special_code)将提供匹配。
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')
带回用户点击量,因为我已经将特殊代码与用户建立了索引。我在映射和更新索引方面做了很多尝试,但没有遇到任何问题。上面的示例有望为工作提供基础。谢谢更新资料
我在布鲁斯的帮助下找到了解决方案。我已经在上面的代码中添加了
mapping
,to_indexed_json
和update_user_index
。
最佳答案
我想您已经在用户模型中具有to_indexed_json和映射?尝试使用after_touch回调更新用户索引。
关于ruby-on-rails - 如何在Tire(retire)中索引模型关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21174063/