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.
Form_with helper in Ruby on Rails
form_with(model: @record, local: true) do |form|
# form fields here
endThe 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.
User model with a text field for the name and a submit button.form_with(model: @user) do |form|
form.text_field :name
form.submit "Save"
end/search URL.form_with(url: '/search', method: :get, local: true) do |form| form.text_field :query form.submit "Search" end
Post model with a text area for content and a default submit button.form_with(model: @post, local: true) do |form| form.text_area :content form.submit end
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.
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 %>
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.
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.