2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[自分用メモ] [Rails] jsのモーダルがキャッシュにより再表示される問題

2
Last updated at Posted at 2026-03-24

環境

  • rails8.1
  • stimulus

発生していた問題

Turbo Drive はページ遷移時に現在のページをキャッシュとして保存します。

そのため、以下のような現象が起きていました。

  1. モーダルを開く
  2. 別のページへ遷移 ← この時点でモーダルが開いた状態のままキャッシュされる
  3. 同じページに戻る ← キャッシュが復元され、モーダルが再び表示されてしまう

解決策

turbo_driveによりモーダルがキャッシュされる前にキャッシュを削除するようにするために、モーダルのjsの記述に下記を入れ、

  // キャッシュの保存する前にモーダルのDOM要素を削除
  beforeCache() {
    this.element.remove()
  }

erb側のdata_acationで設定

data-action="turbo:before-cache@window->modal#beforeCache"

修正後の流れ

  1. 画面遷移時: turbo:before-cache イベント発火
  2. data-action により modal#beforeCache() が呼ばれる
  3. this.element.remove() でモーダルを削除
  4. モーダルなしの状態でキャッシュを保存
2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?