我正在尝试从数据库中的列中获取值的平均值。我在 postgreSQL 数据库中使用 RoR 和 ActiveRecord。
City
与categories
表关联。 categories
表包含多个具有不同名称的记录实例,例如 price_of_coffee
和 price_of_beer
。名为 value
的列包含表示类别价格的字符串
数字。
以下是 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
然后我在 View 文件中显示结果:
<strong>Average Price of a coffee: $</strong>
<%= @average_price_of_coffee %>
我真的很想利用 ActiveRecord 的强大功能并能够使用 Average! 我也有一种感觉,数据库的设置不是最佳的 --- 但我想知道是否有任何可以在不更改数据库的情况下继续前进。救命!
最佳答案
我正在将 Rails 与 PostgreSQL 结合使用。
在询问平均值时,我将其转换为整数,如下所示:
city_categories.average("value::int")
我不知道类型转换在其他数据库上是否相同,但在 Postgres 上可以像你的问题一样工作。
关于ruby - ActiveRecord 值是字符串类型数字的列的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26541933/