I have an N 1 Query issue, but I dont understand how to fix the issue.
I have a User model, Post model and Comment Model.
User has many posts
User has many comments
Post belongs to User
Post has many Comments
Comments belong to user
Comment belongs to post
In my post controller, I have
def index
@posts = Post.includes(:author).where(author_id: params[:user_id])
end
def show
@post = Post.includes(:author).find(params[:id])
end
When I load the Posts show view below...
I get these two warnings from Bullet Gem
user: espada
GET /users/2/posts/6
USE eager loading detected
Comment => [:author]
Add to your query: .includes([:author])
Call stack
user: espada
GET /users/2/posts/6
USE eager loading detected
Comment => [:post]
Add to your query: .includes([:post])
Call stack
I have tried to add the two .includes in various actions, tried many things for the past 5 hours...nothing works. At this point, I want to understand where do I add those two includes?
And how does one interpret that message?
CodePudding user response:
You're probably looking for a dependency on comments, not on posts. So you have to include it like this.
Post.includes(:author, comments: [:author, :post]).find(params[:id])
CodePudding user response:
Its showing an error on the comments model
Try This
def index
@posts = Post.includes(:author, comments: %i[author post]).where(author_id: params[:user_id])
end
def show
@post = Post.includes(:author, comments: %i[author post]).find_by_id(params[:id])
end