0

When I try to do this:

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

and inspect the element:

raise questions.inspect

It returns an array including two same objects, but I expect two different objects in my questions array. What do I do wrong?

sawa
  • 165,429
  • 45
  • 277
  • 381
Furkan Ayhan
  • 1,349
  • 9
  • 16
  • 1
    The error is probably in the implementation of `Question.first` -apparently it's not creating a new `Question` like you expect it to. – Cubic Dec 08 '12 at 18:27
  • I suspect you're getting an object back when you call `Question.first` which just keeps the query around for later retrieval. – Eric Walker Dec 08 '12 at 19:35
  • You can refer to this link for fetching random records: http://stackoverflow.com/questions/2752231/random-record-in-activerecord –  Dec 08 '12 at 19:55

1 Answers1

0

You could try creating a method on Question that returns a random record:

class Question < ActiveRecord::Base

...

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

...

end

Then use:

questions = Array.new
2.times do
  question = Question.random
  questions << question
end
idrysdale
  • 1,551
  • 2
  • 12
  • 23