gpt4 book ai didi

ruby-on-rails - 更改has_many模型时的Rails Elasticsearch重新索引文档

转载 作者:行者123 更新时间:2023-12-02 22:32:52 25 4
gpt4 key购买 nike

我正在使用elasticsearch-rails gems

gem 'elasticsearch-model', '~> 0.1.6'
gem 'elasticsearch-rails', '~> 0.1.6'

我的模型:

place.rb
class Place < ActiveRecord::Base
include PlaceElasticSearch
...
has_many :order_rooms
...
end

orer_room.rb
class OrderRoom < ActiveRecord::Base
belongs_to :place
end

place_elastic_search.rb
require 'elasticsearch/model'

module PlaceElasticSearch
extend ActiveSupport::Concern

included do
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks

index_name "places-#{Rails.env}"

settings INDEX_SETTINGS do
mappings dynamic: 'false' do
...
indexes :order_rooms, type: 'nested', include_in_root: true do
indexes :max_persons, type: 'integer'
end
end
end

after_touch() { __elasticsearch__.index_document }

end
end

创建/删除/更新order_room之后,我需要重新索引放置Elasticsearch文档。

我为order_room模型添加了after_save回调

order_room.rb
after_save :update_place_document

def update_place_document
place.__elasticsearch__.index_document if Place.respond_to?('__elasticsearch__')
end

但是,如果我已经更新或删除了旧的订购室,那是行不通的。

有任何想法吗?我哪里错了?

最佳答案

嗯,好像地方已经缓存了命令室对象。如果我将重新加载添加到after_save方法或place(cache: false)中,则所有方法均有效。还需要添加after_destroy回调

order_room.rb

after_save :update_place_document
after_destroy :update_place_document

def update_place_document
place(cache: false).__elasticsearch__.index_document if Place.respond_to?('__elasticsearch__')
end

关于ruby-on-rails - 更改has_many模型时的Rails Elasticsearch重新索引文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29142427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com