My Controller
class MessagesController < ApplicationController
def index
@messages = Message.all
end
def new
@message = Message.new
end
def create
@message = Message.new(message_params)
if @message.save
redirect_to '/messages'
else
render 'new'
end
end
private
def message_params
params.require(:message).permit(:content)
end
end
My corresponding view
<div class="create">
<div class="container">
<%= form_for(@message) do |f| %>
<div class="field">
<%= f.label :message %><br>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit "Create" %>
</div>
<% end %>
</div>
</div>
I'm a bit confused about how things work under the hood for Rails object creations. Currently doing the Codecademy tutorial, but they've skipped a couple of explanation steps.
When the form submits button is pressed does
f.submit
generate a JSON object in a POST request?After getting routed to the message controllers' create action. How does @message.save know if it's been saved successfully? Isn't it just an object populated by the parameters passed in at this point? Does it route to the DB first before the controller?
CodePudding user response:
You can see what gets submitted by a form submission in your rails server logs. Just run rails server
in a terminal, open up your localhost, submit a form and immediately check what gets spit out in the terminal.
You might get something like this:
Started POST "/messages" for ::1 at 2021-10-25 11:41:33 0200
Processing by MessagesController#create as HTML Parameters: {"message"=>"text", "content"=>"hey"}
[here you will see the SQL run to INSERT new data into the database]
Completed 201 Created in 1ms (ActiveRecord: 2.0ms | Allocations: 2073)
Breaking this down you get 5 pieces of information.
- Type of request and endpoint with a timestamp
- Controller and format used
- Params in JSON
- SQL query run if any
- Response status with benchmarks for parts used in response, how much time queries took, how much rendering took etc.
save
method from rails will try to save an instance of an initialized model into the database and will return true or false depending on the result of the action. There is also save!
method that will raise an error if the operation fails, instead of simply returning false boolean value. So to answer your question specifically:
- JSON object is sent in params of your POST request, generated based on the HTML form.
- @message is an object populated by params (in your case it's only content param that is actually used). Using
save
on it will prompt ActiveRecord to connect to the database and perform an INSERT action, saving it to the database. - It does not route to the DB first, the controller controls the actions performed based on the request. If something hits the database, you will have to prompt it, as you do by using the save method.