DEV Community

Adam La Rosa
Adam La Rosa

Posted on

Forms, ActionView, and the move to form_with

Forms are what make up the user experience online. From logging into your favorite website, to changing what you want to see, to logging out, forms are were most of this work takes place.

Traditionally this has been done with the

html tag. For example:
<form action=“/user” method="get">
  Name: <input type="text" name="name"><br>
  <input type="submit" value="Submit">
</form>

With Ruby on Rails, Action View provides a number of helper methods which make writing out form tags a bit easier, and in some cases directly relate them to the models one could be working with.

form_tag

With embedded Ruby a simple form field can be written out quite easily. For example:

<%= form_tag users_path do %>
  <%= text_field_tag :name %>
  <%= submit_tag %>
<% end %>

Action View makes working with models, and their associated attributes even easier.

form_for

The form_for helper made learning Rails incredibly easier for me. Providing a model in the form & having that form automatically have access to the model’s attributes was a dream come true. For example:

<%= form_for @user do |f| %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %>

The latter uses builder field helpers, a syntax separate from form_tag. But as Rails progresses into newer versions both are being phased out in favor of a combination of the two.

form_with

In the future forms in Rails will be exclusively created with form_with, a helper which looks to combine the functionality of form_for and form_tag into a single method. This in turn creates a bit of extra code on its creation with having to specify the use of a model or not.

In the case of form_with as form_tag

<%= form_with url: users_path do |f| %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %>

…and with form_with accepting a model:

<%= form_with model: @user do |f| %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %>

Personally I am enjoying the switch to form_with & the combination of resources it allows.

Top comments (0)