Created
July 7, 2011 01:50
-
-
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...
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
# ====== 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