フォーム:newとcreate
これまでブラウザは、ページを求めるだけでした。GETです。フォームは何かを送ります。method="post"のHTMLの<form>で、ブラウザが入力欄の中身をリクエストに詰めます。Railsではこれが、規約で名前の決まったアクションの組になります。newは空のフォームを表示し、createは送られてきたものを受け取って保存し、ブラウザを新しいレコードのページへ送ります。これがリダイレクトです。ミニブラウザもブラウザと同じようにフォームを送るので、ここで全部試せます。
アプリとそのデータは、レッスン58のものです。
install_gem "rails"
require "rails"
require "action_controller/railtie"
require "active_record"
# Railsのレッスンと同じアプリです。起動はページごとに一度なので同じクラスを使い、
# フォルダは、まだないときだけ作ります
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.version次に、テーブルとモデルと3つの料理です。
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.countいよいよフォームです。resources :dishesに:newと:createを足すと、7つのルートのうち、さらに2つが増えます。GET /dishes/newとPOST /dishesです。ビューnew.html.erbはform_with model: @dishでフォームを組み立てます。モデルを見れば、どこへ送るか、入力欄をどう呼ぶか(dish[name])がわかるからです。createの中のparams.expect(dish: [:name, :price])は、リクエストからこの2つの欄だけを取り出し、ほかは受け取りません。これがStrong Parametersで、あなたが用意していない列を誰かにこっそり差し込まれないためのものです。そしてsaveです。trueならブラウザはflashのお知らせ付きで料理のページへ送られ、falseならフォームがエラー付きで戻ってきます(ステータス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, "/"「Add a dish」をクリックして、名前を空のまま送ってみてください。フォームがName can't be blankと一緒に戻ってきます。入力した内容はそのままです。今度はきちんと入力してみましょう。ログにはPOST、INSERT、Redirected to http://localhost/dishes/4、そのあとのGETが出て、ページには… is on the menuと、一度だけ表示されます。この文はflashに乗って運ばれました。次のページまでだけセッションに置かれるメッセージです。セッションはクッキーの中にあり、ミニブラウザもブラウザと同じようにクッキーを持ち続けます。フォームの隠し欄authenticity_tokenにも注目してください(POSTのパラメータのログに出ています)。よそのサイトから偽のフォームを送られないためのRailsの守りで、POSTのたびに確かめられます。あなたは何もしなくてかまいません。
bin/rails generate scaffoldがこれを全部書いてくれて、さらにedit、update、destroyも付いてきます。同じフォームのファイルが編集にも使われ(form_withは保存済みのレコードに気づいてPATCHに切り替えます)、削除はdata: { turbo_method: :delete }付きのボタンです。ガイドのお店は、ちょうどここから先へ進みます。レイアウト、パーシャル、ログイン、そして再読み込みなしに変わるページのためのHotwireです。form.label :priceとform.number_field :price, step: 0.1を足して、createが価格も受け取るようにしましょう(expectの行です)。それからミニブラウザで、価格付きの料理を追加してみてください。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])) # 価格はまだ受け取っていません
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"