简体   繁体   English

在Rails ActiveRecord上显示基于参数的计数

[英]On Rails ActiveRecord show count based on parameter

I have some reporting methods throughout my app and in some cases I want to return the count (for a dashboard), and in others, return the full result set for viewing the details of a report. 我在整个应用程序中都有一些报告方法,在某些情况下,我想返回计数(对于仪表板),而在其他情况下,则返回完整的结果集以查看报告的详细信息。

What I'm wondering, is there a way to dynamically choose to show the count (instead of what I'm doing here): 我想知道的是,有一种方法可以动态选择显示计数(而不是我在这里所做的事情):

def get_query_results(reporting_parameters, count_only = true)
    #put together reporting details...
    if count_only
      MyModel.where(query).count
   else
      MyModel.where(query)
    end
end

I considered setting a local variable to the result of my query parameter, and then call count, but that queries the database again (and even if it didn't it could increase memory usage). 我考虑过将局部变量设置为查询参数的结果,然后调用计数,但这会再次查询数据库(即使没有查询也可能增加内存使用)。

Is there a way to do an effective way to do this in one query? 有没有一种方法可以有效地在一个查询中做到这一点? This is one of several queries I have like this in my app, otherwise I wouldn't care. 这是我在应用中喜欢的几个查询之一,否则我不在乎。 Also, I'd use a ternary, but the actual query conditions in my app are much longer than my example here and it makes it unreadable. 另外,我将使用三元数,但是我的应用程序中的实际查询条件比此处的示例长得多,这使其无法读取。

Suppose you are doing this: 假设您正在执行以下操作:

@collection = get_query_results(...)

Then you can do this afterwards instead of inside of the action: 然后,您可以随后执行此操作,而不是在操作内部执行此操作:

@collection.count

And if you like to call another method: 如果您想调用其他方法:

def total_number(collection)
  collection.count
end

@collection = get_query_results(...)
no_of_records = total_number(@collection)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails 4 ActiveRecord的关联计数顺序 - Rails 4 ActiveRecord order by count of association Rails 3 ActiveRecord:按关联计数排序 - Rails 3 ActiveRecord: Order by count on association Rails ActiveRecord按连接表关联的数量排序 - Rails ActiveRecord sort by count of join table associations 客户中的Ruby on Rails ActiveRecord :: StatementInvalid#show - Ruby on Rails ActiveRecord::StatementInvalid in Customers#show Yii2-使用activerecord在gridview中显示关系数据的数量 - Yii2 - show count of relation data in gridview using activerecord Rails + ActiveRecords:如何按日期对记录进行分组并根据条件显示其计数? - Rails+ActiveRecords: How to group records by date and show their count based on a condition? Rails 5 Activerecord:如何在仪表板视图中显示每个“用户”的“记录类型” - Rails 5 Activerecord: How to show 'type of' record per 'user' in a dashboard view 为什么当使用'includes'时Rails ActiveRecord会为'.count'生成'count(distinct model.id)' - Why Rails ActiveRecord generates 'count(distinct model.id)' for '.count' when 'includes' is used 显示基于计数的SQL查询结果 - Show SQL query results based on a count 根据子查询中的计数显示表结果 - Show table results based on count in sub query
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM