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
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
Why the hassle?
Model.order("RANDOM()").first
There are better performance queries over at this question
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
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.