LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】DBから最新データが取得されていない時の対処法

Last updated at Posted at 2022-06-06

初めに

ポートフォリオのライク機能を作成した際に、DBのデータは変更されているのにインスタンスのデータは更新されていなかった。

環境

  • Rails 6.1.4
  • Ruby 2.7.4

結論

SQLキャッシュがされていたので、同じSQLを発行した場合キャッシュされたデータ(更新前のデータ)が返ってきた。

解決方法

SQLキャッシュ

  • 同じクエリが発生すると、データベースへのクエリを実行せずに、キャッシュされた結果を返す
  • SQLキャッシュは、アクションの開始時に作成され、アクションの終了時に破棄されるので、アクションの実行中しか保持されない。

なので、reloadメソッドを利用することでキャッシュを使わずに再取得できます。

like_controller.rb
class LikesController < ApplicationController

  def create
    review = Review.find(params[:review_id])
    like = Like.create(user: current_user, review: review)
    review.reload
    respond_to do |format|
      format.js
      format.html {redirect_to root_path}
    end
  end
end

これにより、SQLが再度発行され最新のデータがDBから取得されます。

参考

SQL キャッシュ - Rails ガイド

0
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
0
0