Skip to content

Instantly share code, notes, and snippets.

@hoitomt
Last active August 29, 2015 14:23
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 hoitomt/7c54a32bc6ba8a60518a to your computer and use it in GitHub Desktop.
Save hoitomt/7c54a32bc6ba8a60518a to your computer and use it in GitHub Desktop.
Create a has and belongs to many relationship in Rails 4.2

This will create a parents table, a kids table and a relationship between the two tables.

  1. Create the Parents table

    bundle exec rails generate model parents fname:string lname:string
    
  2. Create the Kids table

    bundle exec rails generate model kids fname:string lname:string
    
  3. 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_kids is not valid

    bundle exec rails generate migration create_kids_parents
    
  4. 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
    
  5. Run the migrations

    bundle exec rake db:migrate
    
  6. 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
    
  7. 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
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment