Skip to content

Instantly share code, notes, and snippets.

@compwron
Last active August 29, 2015 14:19
Show Gist options
  • Save compwron/2a99d494b489d2cb4a70 to your computer and use it in GitHub Desktop.
Save compwron/2a99d494b489d2cb4a70 to your computer and use it in GitHub Desktop.
polymorphic has_many_through with dependent destroy
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