2014-01-16 23 views
0

您好我正在rails项目中使用退休和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')带回用户打击,因为我在与用户索引的特殊代码。我已经尝试了很多映射和更新索引而没有获得任何命中。上面的例子有希望提供一个工作的基础。谢谢

更新

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

回答

1

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

+0

布鲁斯感谢您的回复。它让脑汁再次流动起来。我的to_indexed_json不正确。我在这个[线程](https://github.com/karmi/retire/issues/898)中偶然发现了我的错误。我会更新我的代码以反映修复。 – MikeV