残りの3つ:edit、update、destroy
レッスン59では料理を追加しました。料理を変えることと、メニューから外すことが、resourcesの知っている7つのアクションのうち、まだ足りない3つです。editは中身の入ったフォームをもう一度表示し、updateは変更を保存し、destroyは削除します。そのうち2つは、ブラウザのフォームでは送れないHTTPメソッド、PATCHとDELETEを使います。そこでRailsはフォームに_methodという欄を隠しておき、ミドルウェアがそれを読みます。あなたが書くのはmethod: :deleteだけです。
アプリとそのデータを、もう一度用意します。
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にonly:がありません。7つのルート全部です。フォームはパーシャルの_form.html.erbに移り、newとeditの両方がrenderで差し込みます。同じform_withが、その料理が保存済みかどうかに気づいて、POST /dishesかPATCH /dishes/1かを選び、ボタンの文字までCreate DishかUpdate Dishにしてくれます。button_to "Delete", @dish, method: :deleteは、ボタン1つのフォームです。そして4つのアクションが料理を探すところから始まるので、before_actionがまとめて一度だけやってくれます。
Rails.root.join("config/routes.rb").write(<<~RUBY)
Rails.application.routes.draw do
root "dishes#index"
resources :dishes
end
RUBY
DinerApp.reload_routes!
views = Rails.root.join("app/views/dishes")
views.mkpath
views.join("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
views.join("_form.html.erb").write(<<~ERB)
<% 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 %>
<% end %>
ERB
views.join("new.html.erb").write(<<~ERB)
<h2>New dish</h2>
<%= render "form", dish: @dish %>
ERB
views.join("edit.html.erb").write(<<~ERB)
<h2>Edit <%= @dish.name %></h2>
<%= render "form", dish: @dish %>
ERB
views.join("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 "Edit", edit_dish_path(@dish) %> ·
<%= link_to "Back to the menu", dishes_path %>
<%= button_to "Delete", @dish, method: :delete %>
ERB
class DishesController < ActionController::Base
before_action :set_dish, only: [:show, :edit, :update, :destroy]
def index
@dishes = Dish.order(:price)
end
def show
end
def new
@dish = Dish.new
end
def create
@dish = Dish.new(dish_params)
if @dish.save
redirect_to @dish, notice: "#{@dish.name} is on the menu."
else
render :new, status: :unprocessable_entity
end
end
def edit
end
def update
if @dish.update(dish_params)
redirect_to @dish, notice: "#{@dish.name} was updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@dish.destroy
redirect_to dishes_path, notice: "#{@dish.name} is off the menu.", status: :see_other
end
private
def set_dish
@dish = Dish.find(params[:id])
end
def dish_params
params.expect(dish: [:name, :price])
end
end
show_browser DinerApp, "/"料理を開いてEditをクリックし、価格を変えて保存してみてください。updateは料理のページへのリダイレクトで答え、ログにはPATCHが出ます。リクエストは_method=patch付きのPOSTとして届き、Rack::MethodOverrideがルートの求めるPATCHに変えたのです。DeleteはDELETEで同じ手を使います。そのあとのリダイレクトは303 See Otherで、そこでDELETEを繰り返すのではなく、一覧をGETするようブラウザに伝えます。これがルートの一覧の全体です。1行から7つのルートが生まれています。
DinerApp.routes.routes.reject(&:internal).each do |route|
target = "#{route.requirements[:controller]}##{route.requirements[:action]}"
puts "#{route.verb.ljust(6)} #{route.path.spec.to_s.ljust(28)} #{target}"
endbin/rails generate scaffold Dish name:string price:decimalが作るものと、ほとんど1行ずつ同じです。scaffoldで作ったアプリのapp/controllers/dishes_controller.rbとapp/views/dishes/を見れば、どの部品にも見覚えがあるはずです。scaffoldはJSONでも答え(/dishes.json)、削除の前に「本当に?」と尋ねます(data: { turbo_confirm: "…" }。TurboはHotwireのうち、ページを再読み込みせずにフォームを送る部分です)。button_to "Delete", dish, method: :deleteを並べて、一覧のページからメニューを減らせるようにしましょう。ミニブラウザは一覧を表示しています。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 ") %>
<%# a Delete button for this dish goes here %>
</li>
<% end %>
</ul>
<%= link_to "Add a dish", new_dish_path %>
ERB
show_browser DinerApp, "/"