我有两个关系为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
如何将此行为设为默认值?我不想避免额外的排序调用。这是可能的,如果可以,怎么样?
答案 0 :(得分:10)
class Band
include Mongoid::Document
has_many :members, :order => :joined.asc
end