我试图从模型中调用时获取特定表与关联数据的所有记录。我尝试了一些不同的选择,但似乎无法弄清楚。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
该指数法作品完美,并包括与每个记录相关的数据,但是当我尝试使用模型中的相关数据获取所有帖子时,我无法开始工作。感谢您的帮助
你试过'Post.joins([:图像,:评论])。all'?您可以在'rails console'中运行''Post.joins([:image,:comment])。to_sql'并查看正在生成的sql。 – Dharam
你需要使用'render json:@ posts.to_json(:include => [:image,:comment])',以便将关联导出到json。 – Dharam