【发布时间】:2013-04-22 15:13:26
【问题描述】:
我需要使用 Rails 和 MongoId 获取一些随机文档。由于我计划拥有非常大的集合,我决定在每个文档中放置一个“随机”字段并使用该字段选择文档。我在模型中写了如下方法:
def random(qty)
if count <= qty
all
else
collection = [ ]
while collection.size < qty
collection << where(:random_field.gt => rand).first
end
collection
end
end
这个函数确实有效,并且集合中充满了 qty 个随机元素。但是当我尝试像这样的范围使用它时:
User.students.random(5)
我明白了:
undefined method `random' for #<Array:0x0000000bf78748>
如果我尝试使该方法类似于我得到的 lambda 范围:
undefined method `to_criteria' for #<Array:0x0000000df824f8>
鉴于我对在 random 之后应用任何其他范围不感兴趣,我如何在链中使用我的方法?
提前致谢。
【问题讨论】:
标签: ruby-on-rails activerecord model mongoid