配置Mongoid关系以返回已排序的对象

时间:2013-09-24 11:52:10

标签: ruby mongodb mongoid dsl queryinterface

我有两个关系为1-n的课程。像这样:

class Band
  include Mongoid::Document
  has_many :members
end

class Member
  include Mongoid::Document
  field :name, type: String
  field :joined, type: Date
  belongs_to :band
end

现在,当我致电band.members时,我获得了成员对象。我想要的是,如果我打电话给band.members.last以获得加入最后一位的会员。我通过为<=>定义Member方法并根据joined排序来实现这一目标:

band.members.sort.last

如何将此行为设为默认值?我不想避免额外的排序调用。这是可能的,如果可以,怎么样?

1 个答案:

答案 0 :(得分:10)

class Band
  include Mongoid::Document
  has_many :members, :order => :joined.asc
end