1
0

パーフェクトRubyonRails備忘録2

Last updated at Posted at 2024-08-13

コントローラのアクションにおけるフック

  • フックは3種類

    • before_action
      • アクション実行前に呼び出される
    • after_action
      • アクション実行後に呼び出される
    • around_action
      • アクションの前後で呼び出される
  • around_actionの使い方

    • around_actionで定義したメソッド内で、アクション内に処理を戻す必要がある。
    class BooksController << ApplicationController
      around_action :action_logger
      # 略
      def action_logger
        logger.info "before_action"
        yield # ここで、アクションに処理が戻される
        logger.info "after_action"
      end
    end
    
    • ブロックを用いて書くことも可能
    around_action do
      logger.info "before_action"
      yield
      logger.info "after_action"
    end
    

ルーティングとリソース

  • CRUD操作は resources :publishers の一行で定義できる
    • rails routesで確認できる
  • 発展的な書き方
resources :publishers do # publisherリソースに対するCRUDアクションが設定
  resources :books # GET /publishers/:publisher_id/books/:id などが設定
  member do
    # publisherリソース個別へのアクションを設定する
    get 'detail' # GET /publishers/:id/detailが設定
  end
  collection do
    # publisherリソース全体へのアクションを設定する
    get 'search' # GET /publishers/searchが設定
  end
end
  • resources以外のルーティングパターン
    • 1ユーザーから見て、リソースが1つしかない場合、 resource というヘルパーが使える

例外処理

  • ユーザーに通知すべき例外処理は、基本的にコントローラが担当する
  • 特定のステータスコードを返す、例外クラスの代表的なもの。
ステータスコード 英語名 例外の種類
400 Bad Request ActionController::BadRequestなど
404 Not Found ActiveRecord::RecortNotFoundActionController::RoutingErrorなど
405 Method Not Allowed ActionController::MethodNotAllowedなど
422 Unprocessable Entity ActiveRecord::RecordInvalid、ActiveRecord::RecordNotSaved、ActionController::InvalidAuthenticityTokenなど
500 Internal Server Error 多くの例外
  • rescue_from

    • 上記以外で、特定のレスポンスを使いたい時に使う
    class LoginFailed < StandardError # 例外クラスを定義する
    end
    
    class ApplicationController < ActionController::Base
      rescue_from LoginFailed, with: :login_failed
      # withで例外発生時に呼ばれるアクションを指定
      
      def login_failed
        render template: "shared/login_failed", status: 401
      end
    end
    
    class LoginController < ApplicationController
      def create
        @user = User.where(name: params[:name], password: params[:password]).find
        raise LoginFailed unless @user
      end
    end
    
    • ここでは、ユーザーログインに失敗した場合、LoginFailed例外クラスを呼び出し、login_failedアクションにより、ユーザーにログイン失敗したことを示している。
1
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
1
0