LoginSignup
23
24

More than 5 years have passed since last update.

viewからcontrollerのメソッドをhelper_methodで呼び出す

Posted at

viewでもcontrollerのメソッドを使いたいときはhelper_methodを使う

controllerでhelper_methodを定義

application_controller.rb
class ApplicationController < ActionController::Base
  helper_method :current_user, :logged_in?

  private

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

  def logged_in?
    !!session[:user_id]
  end
end

viewで呼び出し

home.html.erb
<%= current_user %>
23
24
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
23
24