Reputation: 1524
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.
Upvotes: 1
Views: 179
Reputation: 7405
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)
Upvotes: 1