0
0
Ruby on Railsframework~5 mins

Form_with helper in Ruby on Rails

Choose your learning style9 modes available
Introduction

The form_with helper makes it easy to create forms in Rails. It helps you build forms that send data to your app without writing HTML manually.

When you want to create a form to add or update a record in your database.
When you need a form that works with AJAX for a smoother user experience.
When you want Rails to handle form URLs and HTTP methods automatically.
When you want to keep your form code clean and DRY (Don't Repeat Yourself).
Syntax
Ruby on Rails
form_with(model: @record, local: true) do |form|
  # form fields here
end

The model: option links the form to a specific database record.

Use local: true to submit the form with a normal HTTP request instead of AJAX.

Examples
Creates a form for a User model with a text field for the name and a submit button.
Ruby on Rails
form_with(model: @user) do |form|
  form.text_field :name
  form.submit "Save"
end
Creates a search form that sends a GET request to the /search URL.
Ruby on Rails
form_with(url: '/search', method: :get, local: true) do |form|
  form.text_field :query
  form.submit "Search"
end
Creates a form for a Post model with a text area for content and a default submit button.
Ruby on Rails
form_with(model: @post, local: true) do |form|
  form.text_area :content
  form.submit
end
Sample Program

This example shows a simple Rails controller and view using form_with. The form lets users enter a post's title and body. When submitted, it creates a new post in the database.

Ruby on Rails
class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to @post
    else
      render :new
    end
  end

  private

  def post_params
    params.require(:post).permit(:title, :body)
  end
end

# In app/views/posts/new.html.erb
<%= form_with(model: @post, local: true) do |form| %>
  <div>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </div>
  <div>
    <%= form.label :body %><br>
    <%= form.text_area :body %>
  </div>
  <div>
    <%= form.submit "Create Post" %>
  </div>
<% end %>
OutputSuccess
Important Notes

By default, form_with submits forms using AJAX unless you set local: true.

The helper automatically sets the correct HTTP method (POST, PATCH) based on whether the model is new or existing.

Use form_with instead of older helpers like form_for for modern Rails apps.

Summary

form_with helps you build forms easily in Rails.

It links forms to models and handles URLs and methods automatically.

Use local: true to disable AJAX if you want normal form submission.