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
给您答案?