`Model.first(:order =>'random()')`总是返回相同的对象

时间:2012-12-08 18:24:48

标签: ruby-on-rails ruby activerecord random

当我尝试这样做时:

questions = Array.new
2.times do
  question = Question.first(:order => 'random()')
  questions << question
end

并检查元素:

raise questions.inspect

它返回一个包含两个相同对象的数组,但我希望questions数组中有两个不同的对象。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您可以尝试在Question上创建一个返回随机记录的方法:

class Question < ActiveRecord::Base

...

  def self.random
    if (c = count) != 0
      find(:first, :offset =>rand(c))
    end
  end

...

end

然后使用:

questions = Array.new
2.times do
  question = Question.random
  questions << question
end