Last active
August 29, 2015 14:19
-
-
Save compwron/2a99d494b489d2cb4a70 to your computer and use it in GitHub Desktop.
polymorphic has_many_through with dependent destroy
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
class Fridge < ActiveRecord::Base | |
has_many :soda_ownerships, dependent: :destroy | |
has_many :cokes, through: :soda_ownerships, source: :owner, source_type: 'Coke' | |
has_many :sprites, through: :soda_ownerships, source: :owner, source_type: 'Sprite' | |
end | |
class SodaOwnership < ActiveRecord::Base | |
belongs_to :fridge | |
belongs_to :owner, polymorphic: true | |
belongs_to :coke, class_name: 'owner_type', foreign_key: 'owner_id' | |
belongs_to :sprite, class_name: 'owner_type', foreign_key: 'owner_id' | |
end | |
class Coke < ActiveRecord::Base | |
has_many :fridges, :through => :fridge_ownerships | |
has_many :fridge_ownerships, as: :owner, dependent: :destroy | |
end | |
class Sprite < ActiveRecord::Base | |
has_many :fridges, :through => :fridge_ownerships | |
has_many :fridge_ownerships, as: :owner | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment