ruby-on-rails - Rails 急切负载和限制

标签 ruby-on-rails limit eager-loading

我想我需要类似于 Rails 急切加载的查询的东西,但我无法找到解决方案。

为简单起见,假设永远不会超过 30 个 Person s 在系统中(所以 Person.all 是一个小数据集),但每个人将有超过 2000 条评论(所以 Person.include(:comments) 将是一个大数据集)。

家长会

class Person < ActiveRecord::Base
  has_many :comments
end

child 协会
class Comment < ActiveRecord::Base
  belongs_to :person
end

我需要查询 Person 的列表s 并包括他们的comments ,但我只需要其中的 5 个。

我想做这样的事情:

有限的家长协会
class Person < ActiveRecord::Base
  has_many :comments
  has_many :sample_of_comments, \
    :class_name => 'Comment', :limit => 5
end

Controller
class PersonController < ApplicationController
  def index
    @persons = Person.include(:sample_of_comments)
  end
end

不幸的是,this article声明:“如果您急切地加载具有指定 :limit 选项的关联,它将被忽略,并返回所有关联的对象”

有什么好办法解决这个问题吗?还是我注定要在急切加载 1000 个不需要的 ActiveRecord 对象和 N+1 查询之间做出选择?另请注意,这是一个简化的示例。在现实世界中,我会与 Person 有其他关联, 在同一个 indexcomments 有相同问题的操作. (照片、文章等)。

最佳答案

不管“那篇文章”怎么说,问题在于 SQL 中,您无法在这种情况下以您想要的方式缩小第二个 sql 查询(急切加载),纯粹使用标准 LIMIT

但是,您可以添加一个新列并改为执行 WHERE 子句

  • 将您的第二个关联更改为 Person has_many :sample_of_comments, conditions: { is_sample: true }
  • 添加 is_sample列至 comments
  • 添加 Comment#before_create分配 is_sample = person.sample_of_comments.count < 5 的钩子(Hook)
  • 关于ruby-on-rails - Rails 急切负载和限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9808674/

    相关文章:

    ruby-on-rails - Searchkick rails 地理空间搜索不起作用

    ruby-on-rails - has_many_polymorphs 是什么意思 "Referential integrity violation"?

    sql - 如何使用 DB2 限制 DELETE 中的行数?

    php - 渴望从 Laravel 5.4 中的相关表中的多个值加载第一个项目

    php - Laravel 急切加载 4 个表

    ruby-on-rails - 如何使用 YARD 记录 Rake 任务?

    php使用next按钮限制查询pdo

    mysql - 限制在特定表中使用 Select * in MySQL

    python - SQLAlchemy 急切加载递归模型

    mysql - Rails 验证并发输入的唯一性失败