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

前端 未结 4 1064
北海茫月
北海茫月 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 17:49

    Active record is trying to return "Expense" objects built from the results of your query. But expense objects don't have a totalAmount field, so this is unrequested "bonus data" as far as ActiveRecord can tell. It coud just throw it out, but instead it keeps it for you, with the most forgiving type assumptions it can.

    My suggestions:

    • Don't do this; it isn't the way Active record is supposed to work; the total of the details belongs to whatever is rolling them up; it isn't a detail object itself.
    • If you must treat it as a detail, name the field amount so ActiveRecord knows what to do with it.
    • If you must have the total as its own field, add an accessor in your Expense model like so:

      def total_amount
          totalAmount.to_f
          end
      

      and use it like so: operatingExpenses[1].total_amount in your code.

提交回复
热议问题