I'd like to refactor the following controller using the cache, but I'm having a problem because I don't know how to write it.

def show
    @user = User.find_by (id: params [: id])
    @likes = Like.where (user_id: @ user.id)
    @posts = Post.where (user_id: @ user.id)
    @favorites = Favorite.where (user_id: @ user.id)

After investigating, it is said that it can be done by making full use of preload and eager_load, but there is only an article on the N + 1 problem and it is closed in all directions.
If anyone has any knowledge, please let us know.

  has_many: favorites, dependent:: destroy
  has_many: posts, dependent:: destroy
  has_many: likes, dependent:: destroy
class Post
class Favorite
class Like
  • Answer # 1

    I don't know what the goal is to say "I want to use the cache for refactoring", but I think the N + 1 problem is the answer in terms of reducing the load on the DB.
    @user = User.includes (: likes,: posts,: favorites) .find_by (id: params [: id])
    @likes etc.@ user.likesIt is not necessary to substitute it because it can be taken with, but it is okay.