huzefa biyawarwala
huzefa biyawarwala

Reputation: 657

How are view helpers available in the controllers?

I have come across a bit of confusion regarding the use of view helpers controllers. The kind of scenario I have is:

session_helper.rb:

module SessionsHelper

  # logs in the given user.

  def log_in(user)
    session[:user_id]=user.id
  end

sessions_controller.rb:

class SessionsController < ApplicationController

  def create
    user = User.find_by(email: params[:session][:email].downcase)

    if user && user.authenticate(params[:session][:password])
      log_in user
      redirect_to user
    end
  end

  def destroy
    log_out
    redirect_to root_url()
  end

Now, as per the documentation that I have read, it mentions that helpers are used in views, to reduce the amount of coding to be done there.

My question is: how I am able to use the log_in and log_out methods defined in the session_helper in my controller?

If anyone can clear me on this concept would be very much helpful.

Upvotes: 0

Views: 57

Answers (1)

Alex Antonov
Alex Antonov

Reputation: 15146

Answer on your question:

ActionController::Base.helpers.log_in(user)

But, it's better to place those methods in the controller.

Upvotes: 1

Related Questions