C.J. Bordeleau
C.J. Bordeleau

Reputation: 307

Accessing current_user in controllers

I am trying to access attributes about the current_user inside my controllers.

class MatchfinderController < ApplicationController

  def c(value, t_array)
    t_array.min{|a,b|  (value-a).abs <=> (value-b).abs }
  end

  def show 
    peeps = User.find(:all, :conditions => ["id != ?", current_user.id])
    user_a = []

    peeps.each do |user|  
      user_a.push user.rating    
    end

    closest_rating = c(current_user.rating, user_a)

    @opponent = User.find(:all, :conditions => ["id != ? AND rating = ? ", current_user.id, closest_rating])
  end
end

current_user is working in the view just fine however returns nil in the controller.

Here is my SessionsHelper.

module SessionsHelper

  def sign_in(user)
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end

  def signed_in?
    !current_user.nil?
  end
end

The SessionsHelper is included by ApplicationController

class ApplicationController < ActionController::Base
  protect_from_forgery
  include SessionsHelper
end

Here is my SessionsController

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by_email(params[:email])
    if user && user.authenticate(params[:password])
      sign_in user
      redirect_to root_url, notice: "Logged in!"
    else
      flash.now.alert = "Email or password is invalid"
      render "new"
    end
  end

  def destroy
    cookies[:remember_token] = nil
    redirect_to root_url, notice: "Logged out!"
  end
end

Upvotes: 1

Views: 3823

Answers (2)

Salil
Salil

Reputation: 47482

put your code in application controller and mark it as helper_method in this way you can use that method in both helper as well as controller

helper_method :current_user

def current_user=(user)
  @current_user = user
end

Upvotes: 2

Satya
Satya

Reputation: 4478

I think helpers are only available to the view. Try putting this near the top of your controller:

include SessionsHelper

Upvotes: 0

Related Questions