Skip to content

Instantly share code, notes, and snippets.

@stevenharman
Created July 7, 2011 01:50
Show Gist options
  • Save stevenharman/1068758 to your computer and use it in GitHub Desktop.
Save stevenharman/1068758 to your computer and use it in GitHub Desktop.
Break up multiple associations to the same Model by letting the domain lead the way...
# ====== A naïve model =======
class User < ActiveRecord::Base
has_many :widgets
has_many :purchased_widgets, :class_name => 'Widget'
end
class Widget < ActiveRecord::Base
belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id'
belongs_to :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
end
# ====== Introduce a Purchase model in between =======
class User < ActiveRecord::Base
has_many :widgets, :foreign_key => 'seller_id'
has_many :purchases, :foreign_key => 'buyer_id'
end
class Purchase < ActiveRecord::Base
belongs_to :buyer, :class_name => 'User'
has_one :widget
end
class Widget < ActiveRecord::Base
belongs_to :seller, :class_name => 'User'
belongs_to :purchase
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment