2016-03-29 22 views
0

我试图从模型中调用时获取特定表与关联数据的所有记录。我尝试了一些不同的选择,但似乎无法弄清楚。rails包含获取所有请求中的所有相关数据

我有AA轨道结构,其中: (假设所有的类都继承ActiveRecord:基地)

class Post 
    has_many :image 
    has many :comment 
end 

class Image 
    belongs_to :post 
end 

class Comment 
    belongs_to :post 
end 

基本上,我想所有的所有相关数据的帖子在我的后级(或模型) 。例如:

Post.all (but then here do something to include each post's images and comments) 

我已经试过这两个选项,但他们不返回相关的数据

Post.all.eager_load(:image, :comment) 
Blog2.all.includes(:image, :comment) 

在我的控制器我有一个指数法

def index 
    @posts = Post.all 
    render json: @posts, :include => [:image, :comment] 
    end 

该指数法作品完美,并包括与每个记录相关的数据,但是当我尝试使用模型中的相关数据获取所有帖子时,我无法开始工作。感谢您的帮助

+0

你试过'Post.joins([:图像,:评论])。all'?您可以在'rails console'中运行''Post.joins([:image,:comment])。to_sql'并查看正在生成的sql。 – Dharam

+1

你需要使用'render json:@ posts.to_json(:include => [:image,:comment])',以便将关联导出到json。 – Dharam

回答

1

你很近。 includes方法将预加载关联的数据,但实际上不会将结果呈现给您,除非您明确告诉它。

例如:

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 

这将将数据转换成散列的阵列,适合于发布为JSON。

如果你只需要访问在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 
+0

只需指出,答案只适用于这种特定情况下,响应直接从控制器呈现为json。 – mmhan

+0

@mmhan ok编辑它。你会添加什么? –