dry前
class BookController < ApplicationController
def index
@books = Book.all
end
def show
@book = Book.find(params[:id])
end
def new
@book = Book.new
end
def create
book = Book.new(params[:book].permit(:title, :author))
book.save
redirect_to :root
end
def edit
@book = Book.find(params[:id])
end
def update
book = Book.find(params[:id])
book.update(params[:book].permit(:title, :author))
redirect_to :root
end
def destroy
book = Book.find(params[:id])
book.destroy
redirect_to :root
end
end
dry後
class BookController < ApplicationController
before_action :set_book, only: [:show, :create, :edit, update, :destroy]
def index
@books = Book.all
end
def show
end
def new
@book = Book.new
end
def create
@book = Book.new(book_params)
@book.save
redirect_to :root
end
def edit
end
def update
@book.update(book_params)
redirect_to :root
end
def destroy
@book.destroy
redirect_to :root
end
private
def set_book
end
def book_params
params[:book].permit(:title, :author)
end
end
before_actionでset_bookを適用させた。
privateメソッドで、book_paramsを一つにまとめた