LoginSignup
2
2

More than 5 years have passed since last update.

[rails]controllerのdry for 入門

Last updated at Posted at 2015-08-16

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を一つにまとめた

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2