How to Use the Rails form_for Method

09/20/2021

Contents

In this article, you will learn how to use the Rails form_for method.

Rails form_for Method

The form_for method in Rails is used to generate a form that corresponds to a specific model instance. Here are the basic steps to use the form_for method:

  • In your controller action, create a new instance of the model that the form will correspond to:

    def new
      @user = User.new
    end
    
  • In your view file, use the form_for method to create the form:

    <%= form_for @user do |f| %>
      # Form fields go here
    <% end %>
    

    The form_for method takes the instance variable of the model as its argument. It also takes a block that contains the form fields.

  • Inside the form_for block, use the f variable to create form fields:

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

    In this example, f.label and f.text_field create a label and text input for the user’s name, while f.label and f.email_field create a label and email input for the user’s email. The f.submit method creates a submit button for the form.

  • In your controller, define the action that will handle the form submission:

    def create
      @user = User.new(user_params)
    
      if @user.save
        # Handle successful form submission
      else
        render :new
      end
    end
    
    private
    
    def user_params
      params.require(:user).permit(:name, :email)
    end
    

    In this example, the create action creates a new instance of the User model using the parameters submitted in the form. The user_params method is used to sanitize the parameters and permit only the specified fields.