A form: new and create
So far the browser only asked for pages – GET. A form sends something: an HTML <form> with method="post", and the browser packs the fields into the request. In Rails that is a pair of actions, named by convention: new shows the empty form, create takes what it sends, saves it, and sends the browser on to the new record – a redirect. The mini browser sends forms the way a browser does, so you can try it all here.
The app and its data are those of lesson 58:
install_gem "rails"
require "rails"
require "action_controller/railtie"
require "active_record"
# the app of the Rails lesson: it boots once per page, so this is the same
# class, and its folders are made again only if they are missing
FileUtils.mkdir_p("/tmp/diner/app/views")
FileUtils.mkdir_p("/tmp/diner/config")
routes = "/tmp/diner/config/routes.rb"
File.write(routes, "Rails.application.routes.draw do\nend\n") unless File.exist?(routes)
class DinerApp < Rails::Application
config.root = "/tmp/diner"
config.eager_load = false
config.consider_all_requests_local = true
config.logger = Logger.new(STDOUT)
end
DinerApp.initialize! unless DinerApp.initialized?
Rails.versionThen the table, the model and three dishes:
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "db/diner.sqlite3")
ActiveRecord::Schema.define do
create_table :dishes, force: true do |t|
t.string :name
t.decimal :price, precision: 6, scale: 2
t.timestamps
end
end
class Dish < ActiveRecord::Base
validates :name, presence: true
end
Dish.create!(name: "Bacon", price: 4.5)
Dish.create!(name: "Egg", price: 2)
Dish.create!(name: "Coffee", price: 3.2)
Dish.countNow the form. resources :dishes gets :new and :create, two more of its seven routes: GET /dishes/new and POST /dishes. The view new.html.erb builds the form with form_with model: @dish, which knows from the model where to send it and what to call the fields (dish[name]). In create, params.expect(dish: [:name, :price]) takes exactly those two fields out of the request and nothing else – strong parameters, so nobody can sneak in a column you did not offer. Then save: true, and the browser is sent to the dish's page with a flash notice; false, and the form comes back with the errors (status 422):
Rails.root.join("config/routes.rb").write(<<~RUBY)
Rails.application.routes.draw do
root "dishes#index"
resources :dishes, only: [:index, :show, :new, :create]
end
RUBY
DinerApp.reload_routes!
Rails.root.join("app/views/dishes").mkpath
Rails.root.join("app/views/dishes/index.html.erb").write(<<~ERB)
<h1>Chunky's Diner</h1>
<% if notice %><p><strong><%= notice %></strong></p><% end %>
<ul>
<% @dishes.each do |dish| %>
<li>
<%= link_to dish.name, dish %>
– <%= number_to_currency(dish.price, unit: "CHF ") %>
</li>
<% end %>
</ul>
<%= link_to "Add a dish", new_dish_path %>
ERB
Rails.root.join("app/views/dishes/new.html.erb").write(<<~ERB)
<h2>New dish</h2>
<% @dish.errors.full_messages.each do |message| %>
<p><em><%= message %></em></p>
<% end %>
<%= form_with model: @dish do |form| %>
<%= form.label :name %>
<%= form.text_field :name %>
<%= form.label :price %>
<%= form.number_field :price, step: 0.1 %>
<%= form.submit "Add to the menu" %>
<% end %>
ERB
Rails.root.join("app/views/dishes/show.html.erb").write(<<~ERB)
<% if notice %><p><strong><%= notice %></strong></p><% end %>
<h2><%= @dish.name %></h2>
<p><%= number_to_currency(@dish.price, unit: "CHF ") %></p>
<%= link_to "Back to the menu", dishes_path %>
ERB
class DishesController < ActionController::Base
def index
@dishes = Dish.order(:price)
end
def show
@dish = Dish.find(params[:id])
end
def new
@dish = Dish.new
end
def create
@dish = Dish.new(params.expect(dish: [:name, :price]))
if @dish.save
redirect_to @dish, notice: "#{@dish.name} is on the menu."
else
render :new, status: :unprocessable_entity
end
end
end
show_browser DinerApp, "/"Click "Add a dish", leave the name empty and send: the form returns with Name can't be blank, what you typed still in it. Fill it in: the log shows the POST, the INSERT, Redirected to http://localhost/dishes/4 and the GET that follows – and the page says … is on the menu, once. That sentence travelled in the flash, a message kept in the session just until the next page; the session lives in a cookie, which the mini browser keeps like a browser. Notice the hidden authenticity_token field in the form (look at the log of the POST's parameters): Rails' protection against forged forms from other sites, checked on every POST, with no work on your part.
bin/rails generate scaffold writes all of this, plus edit, update and destroy: the same form file serves editing (form_with notices a saved record and switches to PATCH), and a delete is a button with data: { turbo_method: :delete }. The guide's shop goes on from exactly here: layouts, partials, authentication, and Hotwire for pages that update without a reload.form.label :price and form.number_field :price, step: 0.1 to the view, and let create accept the price too (the expect line). Then add a dish in the mini browser – with a price.Rails.root.join("app/views/dishes/new.html.erb").write(<<~ERB)
<h2>New dish</h2>
<% @dish.errors.full_messages.each do |message| %>
<p><em><%= message %></em></p>
<% end %>
<%= form_with model: @dish do |form| %>
<%= form.label :name %>
<%= form.text_field :name %>
<%# a label and a number_field for the price go here %>
<%= form.submit "Add to the menu" %>
<% end %>
ERB
class DishesController < ActionController::Base
def create
@dish = Dish.new(params.expect(dish: [:name])) # the price is not allowed in yet
if @dish.save
redirect_to @dish, notice: "#{@dish.name} is on the menu."
else
render :new, status: :unprocessable_entity
end
end
end
show_browser DinerApp, "/dishes/new"