简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM