0
0
Ruby on Railsframework~5 mins

Form helpers (form_with) in Ruby on Rails

Choose your learning style9 modes available
Introduction

Form helpers like form_with make it easy to create forms in Rails. They handle HTML form tags and connect forms to your data.

When you want to create a form to add or edit a database record.
When you need a form that submits data to your Rails controller.
When you want Rails to automatically handle form field names and values.
When you want to easily add validations and error messages to forms.
When you want to create forms that work with AJAX for a smoother user experience.
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 data object.

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

Examples
A simple form for a User model with a name field and a submit button.
Ruby on Rails
form_with(model: @user, local: true) do |form|
  form.text_field :name
  form.submit "Save"
end
A form that sends a GET request to a search URL, not tied to a model.
Ruby on Rails
form_with(url: '/search', method: :get, local: true) do |form|
  form.text_field :query
  form.submit "Search"
end
A form for editing an article's content. Defaults to AJAX submission.
Ruby on Rails
form_with(model: @article) do |form|
  form.text_area :content
  form.submit
end
Sample Program

This example shows a Rails controller and view using form_with to create a new article. The form fields match the article's attributes. When submitted, it saves the article or shows errors.

Ruby on Rails
class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article
    else
      render :new
    end
  end

  private

  def article_params
    params.require(:article).permit(:title, :body)
  end
end

# In app/views/articles/new.html.erb
<%= form_with(model: @article, 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 Article" %>
  </div>
<% end %>
OutputSuccess
Important Notes

Always use form_with with a model to get automatic field naming and error handling.

Use local: true if you want a normal form submission instead of AJAX.

Labels improve accessibility by linking text to form fields.

Summary

form_with helps build forms easily in Rails.

It connects forms to models for automatic data handling.

Use local: true to disable AJAX if needed.