prix-fixe

Expand History Expand History
Collapse History Collapse History

Pass model: instead of url: in notes#new

After the previous commit, an invalid submission to the notes#create action results in a re-rendering of the notes#new template. When re-rendering the notes#new template, the controller could pass a reference to the invalid Note instance to pre-populate the <form> element’s fields with the previously submitted values.

Unfortunately, the <form> element in the notes#new template doesn’t use a reference to a Note instance at all. Instead, it passes a value for the url: key to the form_with helper. When the url: key is replaced with a model: key that references an instance of Note, the structure of the request body submitted to POST /notes.

Instead of the FormBuilder building a <textarea> element with name="content", a form_with passed a model: reference uses the Note.model_name to namespace the name attribute with note, and renders <textarea name="note[content]">.

When the server responds to a POST /notes request submitted by such a <form>, the values are nested within a key of that namespace.

In our case, <textarea name="note[content]"> results in strong_params-compliant params helper that can access the content value by chaining #require and #permit:

params.require(:note).permit(:content)