rubymongodbmongoiddsl

Configure Mongoid relation to return objects sorted


I have two classes with a 1-n relationship. Like so:

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

Now when I call band.members I get the member objects. What I want is that if I call band.members.last to get the member who joined the last. I achieve this by defining the <=> method for Member and sort based on joined:

band.members.sort.last

How can I make this behavior default? I don't want to avoid the extra call to sort. Is this possible and if yes, how?


Solution

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