Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way to do counts in Rails?

I have a rails app with many following pieces of code:

Our active community of <%= Account.find_all_by_admin(false).count %>

My question is is this the right way to do counts on views? It seems so "dirty" is there a more railish, way to do counts? I'm thinking named scopes perhaps, but I just want to be sure that these type of things won't have a greater impact in performance.

Thank You,

like image 612
Gotjosh Avatar asked Dec 14 '10 13:12

Gotjosh


People also ask

What is the difference between count length and size rails?

size and . length will include the number of objects you've built but haven't saved, . count will report only the count from the database.

What is Active Record in Ruby?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


2 Answers

You don't need a name scope to perform a count.

Account.where(:admin => false).count

But named scopes are an excellent way to make your code more reusable.

Named scopes don't have any noticeable performance impact on your application.

like image 175
Simone Carletti Avatar answered Sep 26 '22 07:09

Simone Carletti


I would recommend you to avoid direct access to database in my templates because then you're losing a bit of flexibility when it comes to caching.

Try to prepare all the data you need to render in your action instead and then use meaningful instance variables like @number_of_accounts or @accounts.count.

This will make your views cleaner and easier to debug and also a bit more DRY if you render action in different formats (html, json, etc)

As to how do you get your numbers - it doesn't really matter that much, just move away from find_* methods towards scoping and write readable code

like image 30
keymone Avatar answered Sep 22 '22 07:09

keymone