Skip to content

Instantly share code, notes, and snippets.

@prakashmurthy
Last active August 29, 2015 14:10
Show Gist options
  • Save prakashmurthy/825dede6e6b7a489a45a to your computer and use it in GitHub Desktop.
Save prakashmurthy/825dede6e6b7a489a45a to your computer and use it in GitHub Desktop.
Active record find method over-ride
class MyObject < ActiveRecord::Base
...
protected
def self.find(*args)
if results = super(*args)
# Code to add stuff to the my_object.extra_data object
...
end
results
end
end
# One working solution - using after_find callback http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
class MyObject < ActiveRecord::Base
...
after_find :populate_extra_data
protected
def populate_extra_data
self.exta_data = ...
self
end
end
The above is a pattern used in a rails 2.3.18 app I am currently upgrading.
This causes a lot of issues in the higher versions of rails as find method is
not invoked as frequently as it used to be in the 2.3.18 version of rails.
A cursory search for the '.find(' pattern in the activerecord versions show
the following number of instances:
$ grep -ir "\.find(" activerecord-2.3.18/lib | wc -l
98
$ grep -ir "\.find(" activerecord-3.2.18/lib/ | wc -l
37
Even though, most of the occurences are in the comments, it does explain why
my_object.extra_data is nil in many instances.
What would be a good way to refactor this code?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment