Dex
Dex

Reputation: 12749

Rails 3 Returning All Columns from a Join

I'm trying to join two tables and return all columns, not just the ones associated with the model.

I have something like that looks like this:

Comment.joins(:user).select("*")

The SQL looks fine, but still, it only returns the comments and none of the user info associated with it.

How can I retrieve * and not just comments.*?

Upvotes: 6

Views: 6988

Answers (4)

Francis Trujillo
Francis Trujillo

Reputation: 51

Ryan Bates has good tutorial on this subject.

http://railscasts.com/episodes/22-eager-loading-revised?autoplay=true

Upvotes: 1

rwilliams
rwilliams

Reputation: 21497

What about

comments = Comment.includes(:user).all

Now comments is going to be an array so you'll have to loop through it to see all the users.

#won't work
comments.user 

#should work
comments[0].user

comments.each do |comment|
    puts comment.user.name #or whatever
end

Upvotes: 8

Scott
Scott

Reputation: 17257

This should work:

comments = Comment.joins(:user).includes(:user)

But here's what I think is happening, if you are viewing the output in your console windows, I think that the console output only reflects/inspects the root level object that is returned.

I just did an experiment where I executed the above code. The terminal output recorded that it fetched the comments but didn't mention the associated user. Next, I shutdown the database so that a second query could not be executed against the database, then asked for the associated user, e.g.

comments.user

The console output the user, which proves that it has already been eagerly loaded, because no database connection was attempted.

Upvotes: 2

Cory
Cory

Reputation: 2538

Comment.select('*').includes(:user)

Upvotes: 1

Related Questions