0
0
Ruby on Railsframework~5 mins

Model-backed forms in Ruby on Rails

Choose your learning style9 modes available
Introduction

Model-backed forms help you create forms that connect directly to your data. They make saving and updating data easy and organized.

When you want users to create or edit records in your database through a form.
When you want to reuse form code that matches your data structure.
When you want Rails to handle form data validation and error messages automatically.
When you want to keep your code clean by linking forms to models.
When you want to easily display form errors related to your data.
Syntax
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.

Examples
A form for a User model to enter the user's name.
Ruby on Rails
<%= form_for @user do |form| %>
  <%= form.label :name %>
  <%= form.text_field :name %>
  <%= form.submit "Save" %>
<% end %>
A form for an Article model with title and content fields.
Ruby on Rails
<%= form_for @article do |form| %>
  <%= form.label :title %>
  <%= form.text_field :title %>
  <%= form.label :content %>
  <%= form.text_area :content %>
  <%= form.submit %>
<% end %>
A form for a Product model that submits synchronously (not via AJAX).
Ruby on Rails
<%= form_for @product do |form| %>
  <%= form.label :price %>
  <%= form.number_field :price %>
  <%= form.submit "Update Price" %>
<% end %>
Sample Program

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.

Ruby on Rails
# 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 %>
OutputSuccess
Important Notes

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.

Summary

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.