Created
March 7, 2011 14:02
-
-
Save boyvanamstel/858538 to your computer and use it in GitHub Desktop.
Two ways to do many to many relations in RoR
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
# 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