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

标签 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

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

最佳答案

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

关于ruby - 配置 Mongoid 关系以返回排序的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18980876/

相关文章:

javascript - MongoDB 数组在数据库中变成了字符串

ruby-on-rails-3 - Mongoid,与带有时间戳和版本控制的嵌入式文档混淆?

ruby-on-rails - 安装生成器不会看到我定义的方法

ruby-on-rails - 无方法错误 : undefined method `from_json' for "{}":String

ruby-on-rails - Rspec 和 Ruby 中的对象初始化

ruby - Sinatra CSS/图像问题

MongoDB 过滤器(如果所有键都作为字段存在)

ruby - 在 Ruby 中使用单引号和双引号查询哈希有什么区别?

mongodb - MongoDB Stitch 的导入/导出中是否包含依赖项?

MongoDB 获取某年之前日期的记录