ActiveRecord在列上的平均值,其中值是字符串类型的数字

时间:2014-10-24 05:20:58

标签: ruby string postgresql activerecord average

我试图从数据库中的列中获取值的平均值。我在postgreSQL数据库中使用RoR和ActiveRecord。

Citycategories表相关联。 categories表包含多个具有各种名称的记录实例,如price_of_coffeeprice_of_beer。名为value的列包含代表该类别价格的string个数字。

以下是price_of_monthly_utilities的示例记录:

#<Category id: 774, city_id: 2, name: "price_of_monthly_utilities", data: nil, created_at: "2014-10-24 03:33:54", updated_at: "2014-10-24 03:33:54", value: "290">

现在我获取平均值的代码/技术不是很漂亮。

我从cities_controller.rb

调用该方法
@average_price_of_coffee = City.calculate_coffee_price(params[:id])

以下是city.rb模型中的代码:

def self.calculate_coffee_price(id) 
  @coffee_prices = []
  City.find(id).categories.where(name: "price_of_coffee").each do |category| 
    @coffee_prices << category.value.to_f
  end
  @average = (@coffee_prices.sum / @coffee_prices.size).round(2)
end

然后我在视图文件中显示结果:

<strong>Average Price of a coffee: $</strong>
<%= @average_price_of_coffee %>

我真的想利用ActiveRecord的强大功能并且能够使用平均值! 我也有一种感觉,数据库没有最佳设置 - 但我想知道是否有任何进展而不改变数据库。救命啊!

1 个答案:

答案 0 :(得分:2)

我在PostgreSQL中使用Rails。

在询问平均值时我做了一个转换为整数,如下:

city_categories.average("value::int")

我不知道类型转换在其他数据库上是否相同,但在Postgres上工作就像你的问题一样。