Skip to content

Instantly share code, notes, and snippets.

@melriffe
Created February 26, 2012 00:54
Show Gist options
  • Save melriffe/1911966 to your computer and use it in GitHub Desktop.
Save melriffe/1911966 to your computer and use it in GitHub Desktop.
Notes on changing a Many-to-Many to a Self-Referential Many-to-Many
Currently I have Kits and Items. A Kit can contain many Items; an Item can be associated to many Kits.
I also have a join model, KitItem, that allows me to define how many of an Item is associated to a Kit.
Here are the model definitions:
class Kit < ActiveRecord::Base
belongs_to :category
has_many :kit_items, :dependent => :destroy
has_many :items, :through => :kit_items
end
class Item < ActiveRecord::Base
belongs_to :category
has_many :kit_items, :dependent => :destroy
has_many :kits, :through => :kit_items
end
class KitItem < ActiveRecord::Base
belongs_to :item
belongs_to :kit
end
# == Schema Information
#
# Table name: kit_items
#
# id :integer(4) not null, primary key
# quantity :integer(4)
# kit_id :integer(4)
# item_id :integer(4)
# created_at :datetime
# updated_at :datetime
#
# Indexes
#
# index_kit_items_on_item_id (item_id)
# index_kit_items_on_kit_id (kit_id)
#
However, I need to support the concept of a Kit containing other Kits.
I'm not sure how to implement this. The examples I've seen so far are for single table self-joins;
I've only confused myself when attempting to alter them for my purposes.
@bokmann
Copy link

bokmann commented Feb 26, 2012

Mel, sorry to have spun you off in the wrong direction - I had read too much of a previous problem into your situation and thought you were looking for 'peer' kits, as if you were doing suggestions ("Here are Kits like the one you're looking at!"). Jim's comment points you in the right direction, but you can't do a has_many :through a polymorphic relationship. I think this example gives you what you need though:

https://gist.github.com/1915372

@saturnflyer
Copy link

I'm definitely studying this less for the code and more for the magical incantation to summon @bokmann

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