activerecord-如何获取联接表的所有列 [英] activerecord - how to get all column of joined tables
问题描述
阅读后:此
我还是不明白。在控制台中:
I still don't get it. in console:
puts Category.joins(:posts)
它对Category和Post执行联接或左联接。
It perform join or left join on Category and Post.
但是,返回的所有数据只是Category中的列表。如何在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 ?
阅读后:这
是find_by_SQL吗?
after reading: this Is find_by_SQL is the only way ? I want ActiveRecord way if possible.
谢谢。
推荐答案
您可以通过进一步查询来获取帖子表中的列,例如-
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.
这篇关于activerecord-如何获取联接表的所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!