AgentX AgentX - 4 years ago 126
Ruby Question

Ruby On Rails: Understanding Form Submission

I have been previously working on Spring MVC mostly so thought about understanding ROR for a change.

I was going though the tutorials on CodeAcademy, wherein I got a little confused by the following Form Submission mechanism.

So here's a sample form.

<%= 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 %>


The corresponding action handler in Controller is as follows:

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


I am confused by the following line
params.require(:message).permit(:content)

Since
:message
is a label field, it should always have a value. So
.required(:message)
should always be
true
and the method
message_params
should always return the value of the textbox. Correct?

I am not sure if I understand it completely. Could someone explain it a bit clearly.

Answer Source

message is just the label of the content field.

The require(:message) is the parameter hash of your form and permit(:content) is your permitted content parameter. So your parameter hash could look something like this:

{
  message: {
    content: "Your content here..."
  }
}

This technique is called Strong Parameters.

Hope this helps!

Happy coding :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download