Rails平均舍入它自己的

时间:2016-09-06 01:09:38

标签: ruby-on-rails ruby-on-rails-4

我在使用rails 4应用程序中平均一些数据时出现问题,并且输出会自动将数字四舍五入。例如,我想平均一个球员的目标。

[2,3]

哪个应该输出2.5,但它显示2。

控制器

@stats = Stat.where("playerId = ?", @player.playerId).group('year(gameDate)').select('AVG(goals) AS goals')

查看

<% @stats.each do |s| %>
  <%= s.goals %>
<% end %>

我试过了

@goal = Stat.where("playerId = ?", @player.playerId).group('year(gameDate)').average(:goals)

但是得到BigDecimal错误。删除组部分有效,但我需要按年分组。

查询

Player Load (0.3ms)  SELECT  `players`.* FROM `players` WHERE `players`.`id` = 1 LIMIT 1
  CACHE (0.0ms)  SELECT  `players`.* FROM `players` WHERE `players`.`id` = 1 LIMIT 1  [["id", "1"]]
  PlayerStat Load (0.3ms)  SELECT gameDate, AVG(goals) AS goals GROUP BY year(gameDate)  ORDER BY year(gameDate) DESC
Rendered players/_season.html.erb (1.1ms)

1 个答案:

答案 0 :(得分:1)

平均值的返回值将对列的数据类型进行类型转换。如果您的目标列是整数值,则average方法将仅返回整数值。

Reference