Amal Kumar S
Amal Kumar S

Reputation: 16065

Extra count query is running for every normal query in Rails 3. How to fix this

My model is below, when I call this two sql queries are executing one count + original

 class Claim < ActiveRecord::Base


    class << self
      def find_alternatives()
         Drug.where("gpi like '3760%'").select('gpi, drugs.prod_desc_abbrev').group(:gpi)
      end
    end
  end

In my console I find two queries executing

SELECT COUNT(*) AS count_all, gpi AS gpi FROM `drugs` WHERE (gpi like '3760%') GROUP BY gpi

SELECT gpi, drugs.prod_desc_abbrev FROM `drugs` WHERE (gpi like '3760%') GROUP BY gpi

My controller

 def drug_alternatives
    @alternative_drugs = Drug.find_alternatives(params[:gpi])
 end

My Views

 <% @alternative_drugs.each_with_index do |result, count| %>

<%= result.gpi %>
    <%= result.prod_desc_abbrev %>

 <% end %>

How can this be fixed. Why is two queries getting executed?

Upvotes: 4

Views: 239

Answers (2)

Amal Kumar S
Amal Kumar S

Reputation: 16065

Suggested by – Dogbert

in your controller try

@alternative_drugs = Drug.find_alternatives(params[:gpi]).all 

Upvotes: 4

drummondj
drummondj

Reputation: 1483

My guess is, in your view you are using @alternative_drugs.count when you should use @alternative_drugs.size.

Upvotes: 1

Related Questions