Bil*_*lly 4 ruby ruby-on-rails
我试图从模型中调用时获取特定表的所有记录及其关联数据.我尝试了很多不同的选择,但似乎无法弄明白.
我有一个rails结构,其中:(假设所有类都继承自activerecord:base)
class Post
has_many :image
has many :comment
end
class Image
belongs_to :post
end
class Comment
belongs_to :post
end
Run Code Online (Sandbox Code Playgroud)
基本上我想在Post类(或模型)中获取包含所有相关数据的所有帖子.例如:
Post.all (but then here do something to include each post's images and comments)
Run Code Online (Sandbox Code Playgroud)
我已经尝试了这两个选项,但他们没有返回相关数据
Post.all.eager_load(:image, :comment)
Blog2.all.includes(:image, :comment)
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我有一个索引方法
def index
@posts = Post.all
render json: @posts, :include => [:image, :comment]
end
Run Code Online (Sandbox Code Playgroud)
这个索引方法工作得很完美,并且包含了与每条记录相关的数据,但是当我尝试在模型中获取所有帖子及其相关数据时,我无法开始工作.谢谢您的帮助
你很亲密 该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
Run Code Online (Sandbox Code Playgroud)
这会将数据转换为哈希数组,适合作为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
Run Code Online (Sandbox Code Playgroud)