Override 'find' of ActiveRecord::Base
June 17th, 2007
Recently, I was working on one ruby on rails project. where base site has many sub sites based on regions. we required to restrict many queries based on current-region/specific-region. the best solution I figured is add functionality to find method instead of using SQL JOINS.
def self.find(*args)
if args.first == :first || args.first == :all
if args.last.is_a?(Hash) && (region = args.last[:for_region]) && region.is_a?(Region)
with_scope(:find => {:include => [:regionals],
:conditions => "regionals.region_id = #{region.id}"}) do
args.last.delete(:for_region)
super(*args)
end
else
super
end
else
super
end
end
I wrote above code in Business model. now I'm able to
Business.find(:first, :for_region => current_region)
Business.find(:all, :for_region => current_region)
Business.find(:all, :for_region => Region.find(params[:region_id]), Any other valid find option ...)
isn't it cool?
Sorry, comments are closed for this article.