0

Hey guys I want to add a function like this that returns a random record to all the active record models present in my Structure. How do I do this?

  def self.random
   if (c = count) != 0
    find(:first, :offset =>rand(c))
   end
  end
Madhan
  • 498
  • 1
  • 6
  • 19

3 Answers3

1

Why the hassle?

Model.order("RANDOM()").first

There are better performance queries over at this question

Rails 3: Get Random Record

Community
  • 1
  • 1
gmaliar
  • 5,294
  • 1
  • 28
  • 36
  • 1
    Ok, making a fool of myself is checked with that! lol thanks a lot, I will make this the right answer once it lets me. – Madhan Feb 28 '13 at 21:07
0

Even though you can use straight sql, I'll leave this here for future reference about adding class methods to all ActiveRecord objects.

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

Now make sure each model that you want this class method in extends from MyActiveRecordBase

class Model < MyActiveRecordBase
end

class AnotherModel < MyActiveRecordBase
end
Kyle
  • 21,978
  • 2
  • 60
  • 61
  • This is really helpful! Thanks a lot, I will encounter an issue like this in the future thanks! Is there a way to specify the super class when creating the model using rails g? – Madhan Feb 28 '13 at 21:12
  • @MadhanPadmanabhan I'm not sure. If I find a way, I will edit the answer and send you a comment. – Kyle Feb 28 '13 at 21:29
0

Create a module in your /lib folder as models_methods.rb.

Create a method inside this module,

def rand(model)

   model.order("RANDOM()").first

end

def string_to_url(model)

  model.find(2).name.gsub([^A-Za-z0-9],/ /).downcase)

end

Include this module in all your models as "include ModelsMethods". This module can contain all the methods that you want to use across models.

beck03076
  • 3,268
  • 2
  • 27
  • 37