LoginSignup
0
0

More than 1 year has passed since last update.

Railsのコントローラ

Posted at

コントローラの作成コマンド

今回はBooksコントローラを作成します

rails g controller books
Running via Spring preloader in process 51297
      create  app/controllers/books_controller.rb
      invoke  erb
      create    app/views/books
      invoke  test_unit
      create    test/controllers/books_controller_test.rb
      invoke  helper
      create    app/helpers/books_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    scss
      create      app/assets/stylesheets/books.scss

このように表示させると成功です。

BooksControllerを見てみると、
「ApplicationController」を継承しているのが分かります
このApplicationControllerは「app/controllers/application_controller.rb」で定義されています
ここではアプリケーションの全てのコントローラーで共通するヘルパーメソッドや属性などを定義する場所になります

class ApplicationController < ActionController::Base
end

このApplicationControllerはActionController::Baseを継承していて、
コントローラーの大元になっていて、Railsのコントローラーが持つ基本的な機能を提供しています。

Controllerのアクションに対してフックで処理を差し込む

複数のアクションで共通のdestroyアクションを用意する

def show
  @book = book.find(params[:id])
  (省略)
end

def destory
  @book = book.find(params[:id])
  (省略)
end

上記の実装でshowメソッドとdestoryメソッドを見比べるとBook.findが重複しています。
このように同じ処理をメソッドへ抽出し、アクションを呼び出す前や後に実行するフックが用意されています。

「show」「destory」アクションのそれぞれ共通で利用している処理を切り出します。

class BooksController < ApplicationController
  before_action :set_book, only: [:show, :destory]
    def show
      (省略)
    end
    
    def destory
      (省略)
    end
    
    def set_book
      @book = Book.find(params[:id])
    end
end

フックはonlyやexcepといったオプションをつけることができる/
only → 特定のアクション
except → 指定したアクション以外

フックの一覧
before_action→アクションの実行例
after_action→アクションの後
around_action→アクションの前後

0
0
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
0
0