【问题标题】:rails include all associated data in get all requestrails 在获取所有请求中包含所有关联数据
【发布时间】: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


【解决方案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

【讨论】:

  • 只是指出,答案仅适用于响应直接从控制器呈现为json的这种特定情况。
  • @maxpleaner 谢谢,这个答案是救命稻草!有没有办法只获取相关的记录 ID 而不是整个记录?我想我可以用 .pluck 之类的来限制它,但是仍然需要额外的 SQL
  • @Rudi 和 pluck 它只加载您指定的数据。您可以使用select 方法选择任何特定列
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 2020-04-01
  • 2014-04-25
  • 2016-05-21
相关资源
最近更新 更多