【问题标题】:Active Record joined-grouped query on PostgreSQLPostgreSQL 上的 Active Record 联合分组查询
【发布时间】:2012-08-16 02:47:24
【问题描述】:

我在 Rails 项目上工作了一段时间,但遇到了(我认为是)一个小问题。

为了简单起见,我有 3 个这样的模型:

 class House < ActiveRecord::Base
  has_many :house_style_relationships
 end

 class HouseStyleRelationship < ActiveRecord::Base
  attr_accessible :percentage

  belongs_to :style
  belongs_to :house
 end

class Style < ActiveRecord::Base
  has_many :house_style_relationships
end

所以 HouseStyleRelationship 模型只是让我们知道房子的风格百分比。 例如,房子可以是 70% 的现代和 30% 的经典。

我需要做的是获取所有房屋的每种样式的平均值。 为此,我在 SQLite 下使用了这个工作查询:

houses_count = Houses.count
HouseStyleRelationship.joins(:style).select("style.name, SUM(house_style_relationships.percentage)/#{houses_count} as percentage").group("styles.id")

但是当我决定将所有这些东西都推送到 Heroku 时,我遇到了 PostgreSQL 的问题。 事实上,要创建一个 HouseStyleRelationship 对象(我什至不需要),ActiveRecord 会要求一个 HouseStyleRelationship.id ,这会使 Group By 崩溃(使用查询)。 (PostgreSQL 不想对不同 id 的记录进行分组)

您是否有防止 ActiveRecord 生成模型实例作为答案并因此从查询中删除 HouseStyleRelationship.id 的解决方案? (我不能使用 SELECT DISTINCT,因为我需要 SUM() 计算)

提前致谢!

【问题讨论】:

  • 感谢您的详细问题。将来,请尝试包含您的 PostgreSQL 版本以及您收到的任何错误消息的确切文本。

标签: ruby-on-rails ruby postgresql activerecord


【解决方案1】:

您需要创建没有主键的连接表。迁移中的 create_table 语句应如下所示。

create_table :houses_style_relationships, :id => false do |t|

【讨论】:

  • 我想就是这样!我修改了我的模型,使其符合您告诉我使用的未识别关系。接下来我在查询中更改了一些小东西,它可以工作!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多