How to get rails to return SUM(columnName) attributes with right datatype instead of a string?

前端 未结 4 1053
北海茫月
北海茫月 2020-12-30 17:27

Assume a query of the following form

operatingExpenses = Expense.find(:all,
      {:select=>\"categories.activityType, categories.name heading, sum(amount         


        
4条回答
  •  时光取名叫无心
    2020-12-30 18:05

    Just do find_by_sql and apply the SUM on a decimal column :

    operating_expenses = Expense.find_by_sql ['SELECT cat.activityType, cat.name heading, SUM(exp.amount) AS amount FROM expenses exp JOIN expense_categories cat ON exp.category_id = cat.id GROUP BY cat.id, cat.activityType, cat.name, exp.id ORDER BY cat.activityType, amount DESC']
    

    Under the 'amount' column of operating_expenses you'll got your total automatically converted to decimal.

    N.B. : cat.id and exp.id are required to respect SQL standard.

提交回复
热议问题