[英]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.