轨道3:获取随机记录 [英] Rails 3: Get Random Record

查看:285
本文介绍了轨道3:获取随机记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我发现了几个例子查找随机记录在轨道2 - 将preferred方法似乎是:

  Thing.find:一是:偏移=>兰特(Thing.count)
 

被一些新手的我不知道这到底是怎么使用新发现的语法Rails的构造3。

那么,什么是Rails的3路找到一个随机记录?

解决方案

  Thing.first(:为了=>中随机的())#对于MySQL:为了=> RAND(), - 感谢名单,@DanSingerman
#导轨3
Thing.order(RANDOM())。第一
 

  Thing.first(:偏移=>兰特(Thing.count))
#导轨3
Thing.offset(兰特(Thing.count))。第一
 

实际上,在Rails 3的所有示例将工作。但是,为了使用随机是大表,但很慢更SQL风格

So, I've found several examples for finding a random record in Rails 2 -- the preferred method seems to be:

Thing.find :first, :offset => rand(Thing.count)

Being something of a newbie I'm not sure how this could be constructed using the new find syntax in Rails 3.

So, what's the "Rails 3 Way" to find a random record?

解决方案

Thing.first(:order => "RANDOM()") # For MySQL :order => "RAND()", - thanx, @DanSingerman
# Rails 3
Thing.order("RANDOM()").first

or

Thing.first(:offset => rand(Thing.count))
# Rails 3
Thing.offset(rand(Thing.count)).first

Actually in Rails 3 all examples will work. But using order RANDOM is quite slow for big tables but more sql-style

这篇关于轨道3:获取随机记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆