hey mike
hey mike

Reputation: 2471

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.

Upvotes: 15

Views: 17249

Answers (2)

abhishek
abhishek

Reputation: 1008

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.

Upvotes: 4

Ineu
Ineu

Reputation: 1373

You can try select() method:

Category.select("categories.*, posts.*").joins(:posts)

Upvotes: 9

Related Questions