Search code examples
ruby-on-railsrubyruby-on-rails-2

How can i count a column doing a condition?


i'm trying to count a column using conditions

Tables

select* from policies
|policies|
 |id|  |client_id| |expiration_date
   1     1       2013-10-10
   2     1       2013-10-10
   3     2       2013-10-10

|clients|
 |id|  |name|  
   1     ABC       
   2     CDE      
   3     EFG      

i WANT

select *,count(number_expirations) from policies where(client=1)
select *,count(number_expirations) from policies where(client=2)

|policies|
 |id|  |client_id| |number_of_expirations|
   1     1               2
   3     2               1    

This is consult

@count  = Policy.count('expiration_date',:joins=> :client,:conditions=>['name =?',params[:name])

But i'm trying to count expiration_date by client_id

I will really appreciate help.


Solution

  • i did not completely understand your question or the finder that you provided, but i think that you want to get a count of expiration_dates grouped by client.

    this would look like this:

    Policy.where(name: params[:name]).group(:client_id).count