5
6

More than 5 years have passed since last update.

Rails(ORM=Mongoid)でランダムに1件レコードを取得する方法

Last updated at Posted at 2014-09-01

scopeを1行設定するだけの簡単実装

model.rb
class Model
  include Mongoid::Document

  scope :random, -> { skip(rand(self.count)) }

end
1件ランダムに取得する
% rails c
001 > Model.random.first
条件にマッチした中からランダムに取得する
% rails c
001 > Model.where(:age.gt => 18).random.first

実行した環境情報

OS, Kernel

inxi
% inxi -SM
System:    Host: hakuba.vps.sakura.ne.jp Kernel: 2.6.32-279.11.1.el6.x86_64 x86_64 (64 bit)
           Console: tty 5 Distro: CentOS release 6.5 (Final)
Machine:   System: Red Hat product: KVM v: RHEL 6.2.0 PC
           Mobo: N/A model: N/A Bios: Sea v: 0.5.1 date: 01/01/2007

Ruby, Rails

rake_about
% rake about
About your application's environment
Ruby version             2.1.2-p95 (x86_64-linux)
RubyGems version         2.2.2
Rack version             1.5
Rails version            4.1.5

mongoid

mongoid : 4.0.0 - Track your Gems at VersionEye

Rails (800×450)

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6