Creating Common Database Relationships - Gaelan/mrhs-blog GitHub Wiki

Many To Many

For associations where both sides are related to many of the other. For example, Courses and Units where each course will have many units and each unit may be used in more than one course.

  • Generate the scaffold or model (scaffold objects near the top of the hierarchy, generate models for included objects):

    Do this for each model that you are creating, some of the models may already exist if you are making changes to an existing application. Skip this step if both models already exist.

    bin/rails g scaffold Unit title:string soi:text duration:integer
    

    If you are generating a scaffold, you may be prompted to overwrite the file scaffolds.scss:

        create      app/assets/javascripts/units.coffee
        invoke    scss
        create      app/assets/stylesheets/units.scss
        invoke  scss
      conflict    app/assets/stylesheets/scaffolds.scss
    Overwrite /Users/dlu/Source/Ruby/Rails/mrhs-blog/app/assets/stylesheets/scaffolds.scss? (enter "h" for help) [Ynaqdh]
    

    Respond n (don't overwrite).

  • Generate the association model

    bin/rails g model CourseUnit course:belongs_to unit:belongs_to
    
  • Add the associations to the models

    In app/models/course.rb:

    has_many :course_units
    has_many :units, through: :course_units
    

    In app/models/unit.rb:

    has_many :course_units
    has_many :courses, through: :course_units
    
  • Run the migrations

    bin/rails db:migrate