【发布时间】:2016-03-29 02:25:13
【问题描述】:
当从模型调用时,我试图获取特定表的所有记录及其关联数据。我尝试了许多不同的选项,但似乎无法弄清楚。
我有一个 rails 结构,其中: (假设所有类都继承自 activerecord:base)
class Post
has_many :image
has many :comment
end
class Image
belongs_to :post
end
class Comment
belongs_to :post
end
基本上,我想在我的 Post 类(或模型)中获取所有带有所有关联数据的帖子。例如:
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
此索引方法运行良好,并包含与每条记录相关的数据,但是当我尝试在模型中获取所有帖子及其相关数据时,我无法开始工作。感谢您的帮助
【问题讨论】:
-
你试过
Post.joins([:image, :comment]).all吗?您可以在rails console中运行 ``Post.joins([:image, :comment]).to_sql` 并查看正在生成的sql。 -
您需要使用
render json: @posts.to_json( :include => [:image, :comment])才能将关联导出为json。
标签: ruby-on-rails ruby