1

I want to create a method which will find me and an random 'article'. The thing is I have no clue how to iterate through the db, and not to get an exception in case of not found. How I think it would work(I know it isn't a rails-way but I have no other clue) Rand a number from Class.first to Class.last check if it exists(it is possible to be deleted) than return the object by the randomized id.

something like this:

1.9.3p194 :009 > def test
1.9.3p194 :011?>   until Task.exists?(x)
1.9.3p194 :012?>     print "hmmmmmm"
1.9.3p194 :013?>     x = rand(1..10)
1.9.3p194 :014?>     end
1.9.3p194 :015?>   end

(More of the specified criterias will be added when the method works this far)

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bogdan M.
  • 2,161
  • 6
  • 31
  • 53

2 Answers2

1

If you use ActiveRecord than you have to catch RecordNotFound exception and call your method recursively. For other ORMs try to catch other exception.

def ran_find
  x = rand(1..100)
  Task.find(x)
rescue ActiveRecord::RecordNotFound => e
  puts 'hmmmm'
  ran_find
end

Not the best implementation cause x values can be met more than one time. But it works.

Nick Kugaevsky
  • 2,935
  • 1
  • 18
  • 22
  • thank you. :) i'm new to rails and ebcause of the 2.x, 3.x versions even tutorials aren't clear enough somethimes. – Bogdan M. Sep 06 '12 at 23:39
1

People like to use the ActiveRecord :offset option to grab a random record, since it avoids this RecordNotFound exception:

Taken from Toby Hede: Random record in ActiveRecord

offset = rand(Model.count)

rand_record = Model.first(:offset => offset)

Community
  • 1
  • 1
Amir Rubin
  • 850
  • 7
  • 11