开发者

Rails 3 Returning All Columns from a Join

开发者 https://www.devze.com 2023-01-27 09:14 出处:网络
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开发者_如何学JAVA:

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开发者_如何学JAVA:

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.


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


Ryan Bates has good tutorial on this subject.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消