jwhiting
jwhiting

Reputation: 357

Rails joins with select issue

I am trying to follow the mantra of "select only what you need" when making database calls in my rails applications. Currently I am eager loading all users against their posts, however I notice that this selects every column from the user table for each users.

I have tried to use a join instead which offers a much easier way to select what specific attributes I need, however I am using paperclip and the user has_attached_file. I currently haven't found a way to include this in the join.

I was just wondering if anyone had any suggestions or tips on what the best way to load both users and posts is in terms of database performance?

Currently to retrieve users I am simply using this sort of syntax:

Post.all.includes(:user)

Upvotes: 1

Views: 211

Answers (1)

Carl Zulauf
Carl Zulauf

Reputation: 39568

Have you tried Post.eager_load(:user)? Should fetch all the Post fields and all the User fields in a single query, and instantiate AR objects for each. Paperclip attachment would be stored in the user table under 4-5 fields starting with the same prefix. Those should be loaded through Post.eager_load(:user).

The only reason this wouldn't work is if the association between Post and User is polymorphic.

Upvotes: 1

Related Questions