41
36

More than 5 years have passed since last update.

[メモ][Rails]コントローラーのメソッドをヘルパーとしてビューで使う

Posted at

コントローラーにあるメソッドをヘルパーのようにビューで使いたい。

最初に考えていたもの

application_controller.rb
def current_user
  @current_user ||= User.find(session[:user_id])
end
◯◯_controller.rb
before_action :current_user
◯◯.html.haml
= user.name if @current_user

みたいな感じで考えていたのですが、
使う action があるコントローラーすべてに before_action をつけないといけないし、
set_current_user みたいな名前にしないとわかりにくい、けどコントローラー内で使うときは current_user て名前じゃないとわかりにくい。

他にもヘルパーに書き出すのがいいかなーと思いつつも
* ヘルパーにしたいメソッドがこのメソッドだけ
* コントローラーでも使うのでヘルパーとコントローラーの両方に書くとDRYじゃない
* ヘルパーに書いて、それをコントローラーに入れてもいいけど、ヘルパーでActiveRecord使うのは気持ち悪い(個人的に)

解決策

このAPIdockの通りです。これで終わりです。

コントローラーに

helper_method :method_name

を入れるだけでよい!

先程のコードの場合は

application_controller.rb
helper_method :current_user

def current_user
  @current_user ||= User.find(session[:user_id])
end

とすれば

◯◯.html.haml
= user.name if current_user

上記のようにビューで使えます。

複数のメソッドを使うときには

application_controller.rb
helper_method :current_user, user_signed_in?

def current_user
  @current_user ||= User.find(session[:user_id])
end

def user_signed_in?
  current_user != nil
end

こんな感じでカンマ区切りでいけるようです。

41
36
1

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
41
36