Processing Forms

In the figure we can see how the various attributes in the model pass through the controller to the view, on to the HTML page, and back again into the model. The model object has attributes such as name, country, and password. The template uses helper methods to construct an HTML form to let the user edit the data in the model. Note how the form fields are named. The country attribute, for example, maps to an HTML input field with the name user[country].

images/mvc_integration_2.png

When the user submits the form, the raw POST data is sent back to our application. Rails extracts the fields from the form and constructs the params hash. Simple values (such as the id field, extracted by routing from the form action) are stored directly in the hash. But, if a parameter name has brackets in it, Rails assumes that it is part of more structured data and constructs a hash to hold the values. Inside this hash, the string inside the brackets acts as the key. This process can repeat if a parameter name has multiple sets of brackets in it.

Form Parameters

Params

id=123

{ id: "123" }

user[name]=Dave

{ user: { name: "Dave" }}

user[address][city]=Wien

{ user: { address: { city: "Wien" }}}

In the final part of the integrated whole, model objects can accept new attribute values from hashes, which allows us to say this:

 user.​update​(user_params)

Rails integration goes deeper than this. Looking at the html.erb file in the preceding figure, we can see that the template uses a set of helper methods to create the form’s HTML; these are methods such as form_with and text_field.

Before moving on, it’s worth noting that params may be used for more than text. Entire files can be uploaded. We’ll cover that next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.61.16