轨道3:获取随机记录轨道

2023-09-08 15:40:19 作者:。。祭祀WO菛の僾

所以,我发现了几个例子查找随机记录在轨道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))。第一
 
旋转轨迹 如何使用微图APP进行轨迹记录

实际上,在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

 
精彩推荐
图片推荐