Last active
August 29, 2015 14:10
-
-
Save prakashmurthy/825dede6e6b7a489a45a to your computer and use it in GitHub Desktop.
Active record find method over-ride
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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