[英]rails include all associated data in get all request
I am trying to get all records of a specific table with their associated data when called from the model. 我试图从模型中调用时获取特定表的所有记录及其关联数据。 I've tried a number of different options but cant seem to figure it out. 我尝试了很多不同的选择,但似乎无法弄明白。
I have aa rails structure where: (assume all classes are inheriting from activerecord:base) 我有一个rails结构,其中:(假设所有类都继承自activerecord:base)
class Post
has_many :image
has many :comment
end
class Image
belongs_to :post
end
class Comment
belongs_to :post
end
Basically I want to get all the posts with all associated data in my Post class (or model). 基本上我想在Post类(或模型)中获取包含所有相关数据的所有帖子。 For example: 例如:
Post.all (but then here do something to include each post's images and comments)
I've tried these two options but they dont return the associated data 我已经尝试了这两个选项,但他们没有返回相关数据
Post.all.eager_load(:image, :comment)
Blog2.all.includes(:image, :comment)
In my controller I have an index method 在我的控制器中,我有一个索引方法
def index
@posts = Post.all
render json: @posts, :include => [:image, :comment]
end
this index method works perfectly and includes the associated data with each record but when I try to do get all posts with their associated data in the model i cant get to to work. 这个索引方法工作得很完美,并且包含每个记录的相关数据,但是当我尝试在模型中获取所有帖子及其相关数据时,我无法开始工作。 thanks for the help 谢谢您的帮助
You're close. 你很亲密 The includes
method will preload the associated data, but won't actually present it to you with the results unless you specifically tell it to. includes
方法将预加载相关数据,但实际上不会将结果显示给您,除非您明确指出。
For example: 例如:
blog_records = Blog2.all.includes(:image, :comment)
blog_records_with_associations = blog_records.map do |record|
record.attributes.merge(
'image' => record.image,
'comment' => record.comment
)
end
This will convert the data into an array of hashes, suitable for publishing as json. 这会将数据转换为哈希数组,适合作为json发布。
If you just need to access the associated records in Ruby, it's simpler: 如果您只需要访问Ruby中的相关记录,则更简单:
blog_records = Blog2.all.include(:image, :comment)
first_image = blog_records.image # preloaded, no SQL fired
first_comment = blog_records.comment # preloaded, no SQL fired
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.