LoginSignup
0
1

More than 5 years have passed since last update.

多対多の更新の時でもelasticsearchにindex登録する

Last updated at Posted at 2018-03-19

ツッコミとか欲しいのでメモ。

elasticsearch-modelを使っている前提で、記事(Article)モデルとタグ(Tag)モデルがあったとする。
記事にタグを紐づける時

article.tag_ids = [1,2,3]

とやっていた場合,ArticleTagモデルで設定したafter_commitは削除時には実行されない。

after_commit on: [:destroy] do
  # 実行されない
  article.__elasticsearch__.delete_document
  article.__elasticsearch__.index_document
end

紐づける時、tag_ids = [1,2,3]を使わなければいいだけだけどそうもいかない場合、

class Article < ApplicationRecord
  def tag_ids(ids = [])
    super(ids)
    __elasticsearch__.delete_document
    __elasticsearch__.index_document
  end
end

上記のように書くことでなんとなくやりたいことができた。

concernとかに切り出して、tagのところを引数にいい感じのメソッド書けばhoge_idsが増えても対応できそう。
ただ何回もindex登録しまくるのでもっといい方法を探したいところ。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1