Created
August 1, 2011 16:27
-
-
Save agraves/1118459 to your computer and use it in GitHub Desktop.
Rewrite has_many association on the fly
This file contains hidden or 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
# Ever needed to dynamically rewrite the conditions on a has_many association? | |
# This is definitely a hack, but useful if parameterizing or adding scopes are | |
# not practical for whatever reason. | |
class Group < ActiveRecord::Base | |
# Any association will do | |
has_many :people | |
def filter_people(conditions) | |
# All calls to this method after the association is traversed and before a reload | |
# are idempotent. You can reload manually, if you prefer. | |
self.reload | |
# You need to specify the foreign key because (I think) this breaks reflection. | |
(class << self; self; end).instance_eval do | |
has_many :people, :conditions => conditions, :foreign_key => :group_id | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment