2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsのbefore_actionを使わずにシンプルに書く方法

Posted at

before action setter いる? / Good-bye "before action setter"
自分もbefore_actionsetterを定義する書き方は良くないと思っていて、自分の書き方を共有しておく。

class HogesController < ApplicationController
  def show
  end

  def hoge
    @hoge ||= Hoge.find_by!(id: params[:hoge_id])
  end
end

private修飾はせずにviewでもメソッドで呼び出し。

<%= controller.hoge %>

モデルの依存関係も同じように書ける。

class ApplicationController < ActionController::Base
  def current_user
    @current_user ||= User.set_current_user!
  rescue
    # 説明用として書くが、raiseは`set_current_user!`内に記述する。
    raise Unauthorized, 'error message'
  end
end

class BooksController < ApplicationController
  def show
  end

  def book
    @book ||= current_user.books.find_by!(id: params[:book_id])
  end
end

コントローラのクラスやメソッドごとに変数利用の有無をbefore_actionで意識する必要がないし、bookcurrent_userに依存するが記述の順番を意識しなくてよい。

メソッドにしておくとシンプルに書くことができて良い。

2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?