Learn

What did we just do?

We created two models named Tag and Destinations. Then, in the model files, we used the methods has_many and belongs_to to define an association between Tag and Destination.

  • has_many :destinations denotes that a single Tag can have multiple Destinations.
  • belongs_to :tag denotes that each Destination belongs to a single Tag.

The has_many / belongs_to pair is frequently used to define one-to-many relationships. A few examples are:

  • a Library has many Books; a Book belongs to a Library
  • an Album has many Photos; a Photo belongs to an Album
  • a Store has many Products; a Product belongs to a Store

Instructions

1.

Now that there’s an association between Tag and Destination, let’s continue and add columns to the migration files.

Open the migration file in db/migrate/ for the tags table, and add the following columns:

  • a string column called title
  • a string column called image
2.

Next in the migration file for the destinations table, add the following columns:

  • a string column called name
  • a string column called image
  • a string column called description
  • the line t.references :tag
3.

Run the migration to update the database with Tag and Destination.

4.

Open up db/seeds.rb. We’ve added a few items here to seed the database with tags and destinations. Run bundle exec rake db:seed to seed the database with the data in db/seeds.rb.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?