Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created March 16, 2010 18:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/334319 to your computer and use it in GitHub Desktop.
Save ryanflorence/334319 to your computer and use it in GitHub Desktop.
Self-referential model with has_many :through, Rails
class Override < ActiveRecord::Base
belongs_to :recruiter, :class_name => "Rep"
belongs_to :signer, :class_name => "Rep"
end
class Rep < ActiveRecord::Base
# Self-referential relationships through overrides
# overrides this rep gets: `rep.downline_overrides`
has_many :downline_overrides,
:foreign_key => 'recruiter_id',
:class_name => 'Override',
:dependent => :destroy
# overrides this rep is "giving": `rep.upline_overrides`
has_many :upline_overrides,
:foreign_key => 'signer_id',
:class_name => 'Override',
:dependent => :destroy
# people this rep receives an override on `rep.signers`
has_many :signers, :through => :upline_overrides
# people receiving an override on this rep `rep.recruiters`
has_many :recruiters, :through => :downline_overrides
end
@lgsunnyvale
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment