Rails 3 - 范围

时间:2012-11-06 19:41:56

标签: activerecord ruby-on-rails-3.2

我的模型设置与此类似:

class Book < ActiveRecord::Base
  has_many :histories, as: :object
end

class Magazine < ActiveRecord::Base
  has_many :histories, as: :object
end

class Action < ActiveRecord::Base
  belongs_to :object, polymorphic: true

  default_scope order(:done_at)

  # a history contains an action and the time that action 
  # occurred on the object it belongs to
end

现在,我想获得所有对象上发生的5个最新动作的列表。所以我可以这样做:

Action.limit(5)

然而,问题是如果最近在同一本书上发生了两个动作,则将检索这两个动作。我想只检索最新的一个。我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

想出我想要的是群组选项。所以我可以这样做:

Action.group(:object_id).group(:object_type).limit(5)