AnApprentice
AnApprentice

Reputation: 110950

Rails How to Use Include

I have the following:

@comments = @message.comments.roots.order("created_at DESC")

This gets all the the comments for a particular message.

Later in the page I run several:

comment.user.profile_pic.url(:small)

The problem with this is that the save user query is hitting the database over and over.

User Load (0.9ms)  SELECT "users".* FROM "users" WHERE ("users"."id" = 3) LIMIT 1

I'm curious to learn how I can use include to eager load the user info along with the comments above. I tried:

@comments = @message.comments.include(:users).roots.order("created_at DESC")

Suggestions? Thanks

Upvotes: 0

Views: 404

Answers (1)

aceofspades
aceofspades

Reputation: 7586

Since a Comment has only one User, you might try .includes(:user)

Upvotes: 2

Related Questions