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.*
?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With