Nicely done! The app now takes in messages through a form and saves them into the database. How does this work? Let's use the request/response cycle as a guide to trace how a user's request flows through the app.
When you visit http://localhost:8000/messages/new to create a new message, it triggers the first turn of the request/response cycle:
- The browser makes a HTTP GET request for the URL
- The Rails router maps this URL to the Messages controller's
new action. The
new action creates a new
@message and passes it on to the view in app/views/messages/new.html.erb.
- In the view,
form_for creates a form with the fields of the
Then when you fill out the form and press Create, it triggers the second turn of the request/response cycle:
- The browser sends the data to the Rails app via an HTTP POST request to the URL
- This time, the Rails router maps this URL to the
- The create action uses the
message_params method to safely collect data from the form and update the database.
Here we used
link_to to create a link to
/messages/new. Instead of hardcoding
<a> elements, we can use
link_to to generate links:
- the first parameter is the link text
- the second parameter is the URL