Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.*?

like image 494
Dex Avatar asked Nov 27 '10 15:11

Dex


2 Answers

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
like image 178
rwilliams Avatar answered Nov 05 '22 07:11

rwilliams


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.

like image 21
Scott Avatar answered Nov 05 '22 09:11

Scott