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)
If you use ActiveRecord than you have to catch RecordNotFound exception and call your method recursively. For other ORMs try to catch other exception.
Not the best implementation cause x values can be met more than one time.
But it works.