What did we just do?
1. The rails generate model
command created a new model named Message. In doing so, Rails created two files:
- a model file in app/models/message.rb. The model represents a table in the database.
- a migration file in db/migrate/. Migrations are a way to update the database.
2. Open the migration file in db/migrate/. The migration file contains a few things:
- The
change
method tells Rails what change to make to the database. Here it uses thecreate_table
method to create a new table in the database for storing messages. - Inside
create_table
, we addedt.text :content
. This will create a text column calledcontent
in the messages tables. - The final line
t.timestamps
is a Rails command that creates two more columns in the messages table calledcreated_at
andupdated_at
. These columns are automatically set when a message is created and updated.
3. The bundle exec rake db:migrate
command updates the database with the new messages data model. With this command, we instruct the bundler to execute (exec
) a rake task, in this case, migrate
, on the database (db
).
4. Finally the bundle exec rake db:seed
command seeds the database with sample data from db/seeds.rb.
Instructions
Now that we have a model, let’s move on to the second and third parts of the request/response cycle and create a controller and a route.
Generate a controller named Messages
.
In the routes file, create a route that maps the URL /messages
to the Messages controller’s index
action.
Then in the Messages controller (app/controllers/messages_controller.rb), add an index
action:
def index @messages = Message.all end