ruby - ActiveRecord 值是字符串类型数字的列的平均值

标签 ruby string postgresql activerecord average

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

Citycategories 表关联。 categories 表包含多个具有不同名称的记录实例,例如 price_of_coffeeprice_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/

相关文章:

postgresql - Conda 环境中的 Postgres (Ubuntu 14.04)

postgresql - Postgres 角色和用户 - 表的权限被拒绝

ruby - Nokogiri 在段落中查找文本

ruby - 像 Ruby 的 Psyco 库 (Python) 这样的东西存在吗?

javascript - 使用javascript收集html中的前3段

java - 实现语音搜索的最有效方法

ruby-on-rails - ElasticSearch Rails - 设置自定义分析器

arrays - 按数字过滤数组?

从字符串中删除第 n 个空格

json - JDO、org.json.simple.JSONObject 和 PostgreSQL JSON 类型