Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

activerecord - how to get all column of joined tables

After reading : this

I still don't get it. in console:

puts Category.joins(:posts)

It perform join or left join on Category and Post.

However, all data returned is just columns in Category table. How to also get those column data in Post. ?

should I make another model to achieve this ?

after reading: this Is find_by_SQL is the only way ? I want ActiveRecord way if possible.

Thanks.

like image 331
hey mike Avatar asked Feb 27 '12 10:02

hey mike


2 Answers

You can try select() method:

Category.select("categories.*, posts.*").joins(:posts)
like image 107
Ineu Avatar answered Sep 21 '22 18:09

Ineu


You can get columns in posts tables by doing further querying, something like -

Category.joins(:posts).collect{|category| category.posts.map{|post| post.attributes.merge(category.attributes) } }

This will give you a giant list of post and category attributes merged together for each Category.

But the point of doing the join on Category is to get a set of Categories that have certain follow certain join criteria. If we take the next example in the same guide,

Post.joins(:category, :comments)

This also gives you a list of Posts only, but the list contains only the posts that follow the join constraint, which is, they all have a category and a comment.

like image 36
abhishek Avatar answered Sep 21 '22 18:09

abhishek