LoginSignup
6
5

More than 5 years have passed since last update.

railsでコントローラーでセットした変数をモデルから参照する方法

Posted at

モデルにクラス変数を定義してコントローラーでそこにセットし、それを参照する

user.rb
class User < ActiveRecord::Base
   # クラス変数
   cattr_accessor :current
end
application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_current_user

  def set_current_user
    User.current = @user
  end
end

各モデルから User.current でログイン中ユーザーを取得できる。
値がセットされていなかった時死ぬ、管理画面とかで死ぬ、テストも書きづらい、コントローラーとモデルは疎結合なのが正常。
なので利用はおすすめしない

6
5
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
6
5