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

How can I count and select at the same time?


I'm trying to do a select and count at the same time.

This is my code:

@count = Policy.find(:all,:conditions=>['state= 0 AND deleted = 0']

####i want to count all the policies  that has 1 client by document

@count =   Policy.count(:joins => :client,:conditions => ['doc_jur LIKE ? OR doc_nat LIKE ?', "%#{params[:doc]}%","%#{params[:doc]}%" ])

How can I do this in only one line (one action)?

I want:

 SELECT count(*) AS count_all FROM `policies` 
 where state= 0 AND deleted = 0
 INNER JOIN `clients` ON `clients`.id = `policies`.client_id 
 WHERE (doc_jur LIKE '%20535920746%' OR doc_nat LIKE '%20535920746%') 

Solution

  • Try this:

      @count =Policy.count(:joins => :client,:conditions => ['policies.state=0 AND policies.deleted= 0 AND clients.doc_jur LIKE ? OR clients.doc_nat LIKE ?', "%#{params[:doc]}%","%#{params[:doc]}%" ])