DEV Community

John Paul Fababaer
John Paul Fababaer

Posted on

Sprint 4: Ruby on Rails - Helper Methods for Forms

More helpers! Now we focus on using helper methods to create our form tags in our view template files:

Part 1: using form_with + form builder object (contains the form Object with a bunch of methods to create our tags i.e. ".label") for POST requests.

<%= form_with(model: @movie, data: { turbo: false }) do |form| %>
  <div>
    <%= form.label :title %>

    <%= form.text_field :title,  %>
  </div>

  <div>
    <%= form.label :description %>

    <%= form.text_area :description, { rows: 3 } %>
  </div>

  <%= form.button "Create Movie" %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

Part 2: for a PATCH request, we alter the form_with slightly by adding "method: :patch"

<%= form_with(model: @movie, method: :patch, data: { turbo: false }) do |form| %>
Enter fullscreen mode Exit fullscreen mode

NOTE: the beauty of using the form_with helper method is that it automatically add the extra < input > tags we need to protect ourselves from CSRF attacks.

NOTE 2: form_with also handles the setting of attributes for="" and id="" which defaults to "title" and "description. Therefore, we do NOT need to add this option as long as we follow convention.

NOTE 3: by using the argument "model: ", the form Object is associated with the ActiveRecordObject.

-Therefore, this knows to reference that Movie Instance to access the columns we are referencing for values.
-In that same way, we can drop the prepopulated values, Rails will do it for us since it just has to look at the Instance Object and match it with our defined symbol column.

CY@. I'm confused. Lol.

Top comments (0)