Skip to content

Instantly share code, notes, and snippets.

@agraves
Created August 1, 2011 16:27
Show Gist options
  • Save agraves/1118459 to your computer and use it in GitHub Desktop.
Save agraves/1118459 to your computer and use it in GitHub Desktop.
Rewrite has_many association on the fly
# 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