activerecord - how to get all column of joined tables

走远了吗. 提交于 2020-01-12 03:27:07

问题


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.


回答1:


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.




回答2:


You can try select() method:

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


来源:https://stackoverflow.com/questions/9463211/activerecord-how-to-get-all-column-of-joined-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!