Rails 3 Return All Columns from a List

I am trying to join two tables and return all columns, not just the ones that are associated with the model.

I have something like this:

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

SQL looks great, but still it only returns comments and not a single user information related to it.

How can I get * , not just comments.* ?

+6
join ruby-on-rails arel
source share
4 answers

What about

 comments = Comment.includes(:user).all 

Now comments will be an array, so you will need to skip it to see all users.

 #won't work comments.user #should work comments[0].user comments.each do |comment| puts comment.user.name #or whatever end 
+7
source share

This should work:

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

But here is what I think happens if you view the output in your console windows, I think that the output to the console reflects / checks the returned root level object.

I just did an experiment where I executed the above code. The terminal output says that he received comments, but did not mention the associated user. Then I complete the database so that the second query could not be executed against the database, and then asked the associated user, for example.

 comments.user 

The console displays the user, which proves that it has already been loaded, because the connection to the database has not been attempted.

+2
source share
.

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

+1
source share
+1
source share

All Articles