Search code examples
ruby-on-rails-3postgresqlrails-postgresql

How do I .group and .sum in a rails model using Postgres?


I have a functioning method in my development environment (SQLite) that looks this:

def self.ytd
Production.find(
    :all,
    conditions: ["year == ?", Time.now.year],
    select: "carrier_id, amount, SUM(amount) as sum_amount",
    group: :carrier_id
    )
end

This method successfully searches through a table consisting of :carrier_id and :amount columns. It then sums the :amount column based on the grouped :carrier_id

I am trying to convert to a production environment using Postgresql. The below code successfully groups the records however I cannot sum the :amount. I have tried amending .sum("productions.amount") to the method without success. I am sure there is a simple solution, but it alludes me.. can someone please help? Thanks

def self.ytd
Production.select("DISTINCT ON (productions.carrier_id) productions.carrier_id, productions.amount ")
               .where("productions.year = (?)", "#{Time.now.year}")
               .group("productions.amount, productions.carrier_id, productions.id")
end

Solution

  • Removed DISTINCT ON, added SUM(amount) as sum_amount and grouped on :carrier_id yielded the desired results.

    def self.ytd
    Production.select("productions.carrier_id, SUM(amount) as sum_amount")
                   .where("productions.year = (?)", "#{Time.now.year}")
                   .group("productions.carrier_id")      
    end