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,
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With