This will create a parents table, a kids table and a relationship between the two tables.
-
Create the Parents table
bundle exec rails generate model parents fname:string lname:string
-
Create the Kids table
bundle exec rails generate model kids fname:string lname:string
-
Create the Join table between parents and kids. NOTE the naming order is important: Rails expects it to be named in alphabetical order.
kids_parents
is valid.parents_kid
s is not validbundle exec rails generate migration create_kids_parents
-
Update the migration so that the proper columns are created
class CreateKidsParents < ActiveRecord::Migration def change create_table :kids_parents, id: false do |t| t.integer :kid_id t.integer :parent_id end end end
-
Run the migrations
bundle exec rake db:migrate
-
Update the models
class Kid < ActiveRecord::Base has_and_belongs_to_many :parents end class Parent < ActiveRecord::Base has_and_belongs_to_many :kids end
-
Add some test data and try it out
bundle exec rails c homer = Parent.create(fname: "Homer", lname: "Simpson") marge = Parent.create(fname: "Marge", lname: "Simpson") bart = Kid.create(fname: "Bart", lname: "Simpson") lisa = Kid.create(fname: "Lisa", lname: "Simpson") homer.kids << [bart, lisa] marge.kids << [bart, lisa] homer.kids #this should return an array with bart and lisa bart.parents #this should return an array of marge and homer