How to get count of records from database?


#1

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


#2

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


#3

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/Calculations/ClassMethods.html#M000823

-Jonny.


#4

Controller

@cheese_number = Cheese.count(:conditions => “colour = ‘red’”)

View

<%= @cheese_numer %>

Cheers

Jonathan

http://www.agileevolved.com