Model-backed forms help you create forms that connect directly to your data. They make saving and updating data easy and organized.
Model-backed forms in Ruby on Rails
<%= form_for @model_instance do |form| %> <%= form.label :attribute %> <%= form.text_field :attribute %> <%= form.submit %> <% end %>
Use form_for @model_instance to link the form to a model object.
The form fields automatically match the model's attributes.
<%= form_for @user do |form| %>
<%= form.label :name %>
<%= form.text_field :name %>
<%= form.submit "Save" %>
<% end %><%= form_for @article do |form| %> <%= form.label :title %> <%= form.text_field :title %> <%= form.label :content %> <%= form.text_area :content %> <%= form.submit %> <% end %>
<%= form_for @product do |form| %>
<%= form.label :price %>
<%= form.number_field :price %>
<%= form.submit "Update Price" %>
<% end %>This example shows a simple form to create a new Book record. The form fields match the Book model's attributes. When submitted, it tries to save the book and either redirects or shows the form again if there are errors.
# app/controllers/books_controller.rb class BooksController < ApplicationController def new @book = Book.new end def create @book = Book.new(book_params) if @book.save redirect_to @book else render :new end end private def book_params params.require(:book).permit(:title, :author) end end # app/views/books/new.html.erb <%= form_for @book do |form| %> <div> <%= form.label :title %><br> <%= form.text_field :title %> </div> <div> <%= form.label :author %><br> <%= form.text_field :author %> </div> <div> <%= form.submit "Create Book" %> </div> <% end %>
Model-backed forms automatically set the correct URL and HTTP method for creating or updating records.
If the model has errors, Rails can display error messages next to the form fields.
Use strong parameters in the controller to allow only safe attributes.
Model-backed forms link your form directly to your data model.
They simplify form creation, validation, and error handling.
Use form_for @model to create these forms easily.