Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何使用活动记录关联添加计数?_Ruby On Rails_Ruby_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 如何使用活动记录关联添加计数?

Ruby on rails 如何使用活动记录关联添加计数?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我的要求是发送具有活动记录关联的数据库的计数大小 我试图限制记录的大小,希望加载更多选项,单击“加载更多”将显示所有记录 records = company.public_send(table).joins(:customer).where(customer_id: ids).order(sorting) #records = records.count(:id) #300 records = records.limit(5) 这个返回我的活动记录,连同这个我想发送整个大小的记录 我该怎么做呢

我的要求是发送具有活动记录关联的数据库的计数大小

我试图限制记录的大小,希望加载更多选项,单击“加载更多”将显示所有记录

records = company.public_send(table).joins(:customer).where(customer_id: ids).order(sorting)
#records = records.count(:id) #300
records = records.limit(5)
这个返回我的活动记录,连同这个我想发送整个大小的记录
我该怎么做呢?

我认为您应该通过使用两个查询使用直接的解决方案:

  • 选择一个
  • 总计数为1
与其他解决方案相比,这是最简单的解决方案,而且很容易理解

第二,我认为任何分页都可以,但是如果你没有使用所有的功能,那就不值得了

不仅限于此,您仍然可以执行一个查询,但计数将链接到每个记录,并且性能也不会有任何改善

# Ref: https://stackoverflow.com/a/17206119/1600046
records = company.public_send(table).joins(:customer).where(customer_id: ids).order(sorting)
records = records.select("table_name.*, COUNT(*) OVER () as total").limit(1)
records.first.try(:total) # in case empty record

使用一个查询的唯一方法是使用除之外的
,我认为这不是最干净的方法,但可以满足您的需要


那么,在您的情况下,
total_count=records.limit(5)。除了(:limit).count

您正在寻找分页吗?不,我只想知道数据库中记录的总大小,以及有限的记录@sureshprasanna70不会
company.customers.count
给您答案?