开发者

activerecord sum returns a string?

开发者 https://www.devze.com 2023-01-18 09:21 出处:网络
This seems very strange to me, an active record sum returns a string, not a number basket_items.sum(\"price\")

This seems very strange to me, an active record sum returns a string, not a number

basket_items.sum("price")

Th开发者_StackOverflowis seems to make it work, but i thought i may have missed something, as this seems like very strange behaviour.

basket_items.sum("price").to_i


According to the (rails 2.3.9) API:

The value is returned with the same data type of the column, 0 if there’s no row

Could your price column be a string or text?


https://github.com/rails/rails/pull/7439

There was a reason it returned a string - calling to_d on a Fixnum in Ruby 1.8 would give a NoMethodError. This is no longer the case in Ruby 1.9 so it's probably okay to change.


ActiveRecord sum:

Difference:

1) basket_items.sum("price")

It will also sum non integer also and it will return non integer type.

2) basket_items.sum("price").to_i

This above will convert into integer.

# File activerecord/lib/active_record/relation/calculations.rb, line 92
def sum(*args)
  if block_given?
    self.to_a.sum(*args) {|*block_args| yield(*block_args)}
  else
    calculate(:sum, *args)
  end
end

Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there’s no row.

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-sum

Github:

https://github.com/rails/rails/blob/f8f4ac91203506c94d547ee0ef530bd60faf97ed/activerecord/lib/active_record/relation/calculations.rb#L92

Also see, Advanced sum() usage in Rails.

0

精彩评论

暂无评论...
验证码 换一张
取 消