Skip to content

Instantly share code, notes, and snippets.

@boyvanamstel
Created March 7, 2011 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boyvanamstel/858538 to your computer and use it in GitHub Desktop.
Save boyvanamstel/858538 to your computer and use it in GitHub Desktop.
Two ways to do many to many relations in RoR
# http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off
# Join Table: Simple Associations
# Table:
create_table "dancers_movies", :id => false do |t|
t.column "dancer_id", :integer, :null => false
t.column "movie_id", :integer, :null => false
end
# Models:
class Dancer < ActiveRecord::Base
has_and_belongs_to_many :movies
end
class Movie < ActiveRecord::Base
has_and_belongs_to_many :dancers
end
# Join Model: Rich Associations
# Table:
create_table "appearances", do |t|
t.column "dancer_id", :integer, :null => false
t.column "movie_id", :integer, :null => false
t.column "character_name", :string
t.column "dance_numbers", :integer
end
# Models:
class Appearance < ActiveRecord::Base
belongs_to :dancer
belongs_to :movie
end
class Dancer < ActiveRecord::Base
has_many :appearances, :dependent => true
has_many :movies, :through => :appearances
end
class Movie < ActiveRecord::Base
has_many :appearances, :dependent => true
has_many :dancers, :through => :appearances
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment