What did we just do?
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:
changemethod tells Rails what change to make to the database. Here it uses the
create_tablemethod to create a new table in the database for storing messages.
create_table, we added
t.text :content. This will create a text column called
contentin the messages tables.
- The final line
t.timestampsis a Rails command that creates two more columns in the messages table called
updated_at. These columns are automatically set when a message is created and updated.
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 (
4. Finally the
bundle exec rake db:seed command seeds the database with sample data from db/seeds.rb.
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
In the routes file, create a route that maps the URL
/messages to the Messages controller’s
Then in the Messages controller (app/controllers/messages_controller.rb), add an
def index @messages = Message.all end