0

我正在尝试将聚合表与其代表的对象类型连接起来。

这是聚合表的简化模式:

聚合表

aggregate_table[0] => {
  item_type: 'cars',
  item_id: 8,
  count: 12,
  time: 'Thu, 01 Nov 2012 00:00:00 PDT -07:00'
}

aggregate_table[1] => {
  item_type: 'people',
  item_id: 23,
  count: 48
  time: 'Thu, 01 Nov 2012 00:00:00 PDT -07:00'
}

是否可以返回与从 AggregateTable 获取的各自计数合并的Car对象?

这是一个更具描述性的现实生活用例:

  1. 查询聚合表 where item_type: people,具有特定的给定数据范围和按计数排序的结果。

  2. People模型中查询聚合表查询返回的item_ids 。

  3. 将People对象与相应的聚合表结果合并,例如:People#count

我尝试使用左外连接来实现这一点是徒劳的。这样做的正确方法是什么?


运行 PostgreSQL 9.1 和 Rails 3.2.8

4

1 回答 1

2

您应该使用多态关联

Class Aggregation < ActiveRecord::Base
  belongs_to :item, :polymorphic => true
end

并在关联类中包含has_one反向关联(不是必需的,但可能有用)。

有关确切的数据库架构,请参阅上面的文档。

那么对于你的问题:

1我不确定您所说的“特定给定数据”,但您可以通过以下方式查询聚合:

Aggregation.where(:item_type => "People").order(:count)

2以下行将为您提供结果人员(您应该使用 Person/people,Rails 约定)

Aggregation.where(:item_type => "People").order(:count).map(&:item)

或者

People.joins(:aggregation).order("aggregations.count")

您应该能够在或两者上使用Aggregation条件People

3我不确定你是否真的需要“合并”。以下行count将从aggregations表中为您提供:

People.joins(:aggregation).order("aggregations.count").each do |p|
  puts p.aggregation.count
end

您也许应该添加一个includes(:aggregation)以避免每个“人”的查询。

如果您希望能够写作p.count而不是在课堂p.aggregation.count上使用:delegatePeople

class People
  delegate :count, :to => :aggregation
end
于 2012-12-05T16:37:26.173 回答