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
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 calledtitle
- a
string
column calledimage
Next in the migration file for the destinations table, add the following columns:
- a
string
column calledname
- a
string
column calledimage
- a
string
column calleddescription
- the line
t.references :tag
Run the migration to update the database with Tag and Destination.
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.