Override ActiveRecord find
I have done this in Rails 2.3.10 and 3.0.3 and it works
def self.find(*args)
records = super
# Manipulate Records here.
end
I am looking for a base finder function in Rails 3 which I can replace for开发者_运维知识库 this functionality to be applied to Post.all, Post.first, Post.last etc.
My advice ... make a scope or a class method to do this instead:
e.g.
scope :my_scope, lambda {|...| ...}
then to apply
TheClass.my_scope.all
TheClass.my_scope.first
TheClass.my_scope.last
all
, first
, and last
are all just wrappers for find
so redefining find
should affect all of those. Take a look at how they're implemented in ActiveRecord::FinderMethods.
I believe you are looking for this:
# File activerecord/lib/active_record/relation/finder_methods.rb, line 95
def find(*args)
return to_a.find { |*block_args| yield(*block_args) } if block_given?
options = args.extract_options!
if options.present?
apply_finder_options(options).find(*args)
else
case args.first
when :first, :last, :all
send(args.first)
else
find_with_ids(*args)
end
end
end
This will do what the original question was asking.
def self.find_by_sql(*args)
records = super
# Manipulate Records here
return records
end
精彩评论