When to Use form_for and form_tag

Luke Gill
2 min readApr 1, 2021

--

Photo by Kevin Woblick on Unsplash

Rails can be hard.

There are loads of methods and background metaprogramming going on that you won’t see unless you look carefully at the docs, the repo, or payed attention in those lessons you purchased.

One of the things (which is now a little outdated) that is commonly used are the methods called form_for and form_tag. These are mainly used to dynamically create an HTML Form tag <form>and nest other relevant tags such as your link tags <a>, input fields <input>, etc.

Let’s start with form_tag.

form_tag

The basic layout of using form_tag is this

<%= form_tag("/users") do %>
<%= label_tag('user[name]', "Name") %>
<%= text_field_tag('user[name]') %>

<%= label_tag('user[job]', "Job") %>
<%= text_field_tag('user[Job]') %>

<%= submit_tag "Create User" %>
<% end %>

Form_tag takes in two arguments, the path you’re creating the form for, and the route method in which you want to execute. While you can specify whether you want to use patch or delete for form_tag, you will generally not use form_tag for such requests, and let rail automatically know whether to post, or get the form.

form_for

Now this is a more robust helper method. One of the drawbacks of using form_tag is that the form won’t know (unless specifically stated) if hitting the submit button will be updating or posting the form. Form_for keeps things more dry by abstracting even more of the HTML code detecting which route method it will execute based on the first argument of form_for.

<%= form_for(@user) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :job%>
<%= f.text_field :job %>
<%= f.submit "Submit"%>
<% end %>

As you can see, form_for can take in an instance variable as its argument. That instance variable is directly connected to an object declared in the associated action in my controller.

def new
@user = User.new
end

Using a new instance of the user model, we create fields that are connected to our User model’s table (name and the job), and use it to submit the field’s attributes to our database.

In other words, form_for is used when you want to make a form for something. Typically you’ll use form_for more frequently, as many of the forms you will create will be associated with some type of data, i.e. a user login, signup, or an item’s edit form.

So as you can see, there are particular circumstances where you would use one over the other. I hope this clears some things up!

--

--

Luke Gill
Luke Gill

Written by Luke Gill

Software Engineer in training

No responses yet