2008年7月20日 星期日

find random offset

http://blog.pbg4.org/2008/1/2/find-randomly-redux
http://wiki.rubyonrails.org/rails/pages/HowtoSelectRandomRecords
http://groups.google.com/group/Ruby-on-Rails-Taiwan/browse_thread/thread/27ec511fa258ca08
http://blog.commonthread.com/2007/12/7/tip-ruby-on-rails-random-array-element

目前一般的最佳解是這個, random 出offest
def self.find(*args)
scope = args.first
if scope.to_s == "random"
super :first, :offset => (rand count).to_i
elsif scope.to_s == "public"
# blah, blah...
else
super
end
end
ps:console下
Record.find(:first, :offset => (rand Record.count).to_i)

要用Record.count, sometimes some record would be deleted
ps2:bad way find(rand(count) + 1) rescue ActiveRecord::RecordNotFound random

沒有留言: