我试图从数据库中的列中获取值的平均值。我在postgreSQL数据库中使用RoR和ActiveRecord。
City
与categories
表相关联。 categories
表包含多个具有各种名称的记录实例,如price_of_coffee
和price_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的强大功能并且能够使用平均值! 我也有一种感觉,数据库没有最佳设置 - 但我想知道是否有任何进展而不改变数据库。救命啊!
答案 0 :(得分:2)
我在PostgreSQL中使用Rails。
在询问平均值时我做了一个转换为整数,如下:
city_categories.average("value::int")
我不知道类型转换在其他数据库上是否相同,但在Postgres上工作就像你的问题一样。