Forum: Ruby on Rails How to get count of records from database?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8c70506408fddb9740b4de7339055c77?d=identicon&s=25 Prashant Tiwari (tiwaripk)
on 2006-05-08 13:51
Hi,

I want to display count of all records with particular field value from
database onto my view. How should I do that?
PLs tell me.
Thanx.
Prash
7fc62c7ce136d50a68b13beb00765218?d=identicon&s=25 Piers (Guest)
on 2006-05-08 13:58
> I want to display count of all records with particular field value from
> database onto my view. How should I do that?

I think you can do it as follows:

in yr controller:

@count = [model_to_be_queried].find(:all, ["field_name = ?",
value]).size

and then use <%=h @count %> in your view

So for all records in your chicken table with 10 eggs

@count = Chicken.find(:all, ["eggs = ?", 10]).size
631d1677786f0725da6ccee46043686e?d=identicon&s=25 Jonathan Viney (Guest)
on 2006-05-08 14:42
(Received via mailing list)
If you only want the number of records it will be a lot faster to use
count rather than find as AR won't have to instantiate all the
objects.

Person.count :conditions => ['age = ?', 29]

http://api.rubyonrails.org/classes/ActiveRecord/Ca...

-Jonny.
40a94646462b58d8b0109b5fa6655c72?d=identicon&s=25 Jonathan Conway (Guest)
on 2006-05-08 14:45
(Received via mailing list)
Controller
=========
@cheese_number = Cheese.count(:conditions => "colour = 'red'")

View
====
<%= @cheese_numer %>

Cheers

Jonathan
------
http://www.agileevolved.com
This topic is locked and can not be replied to.