0

I have a helper module:

module SessionsHelper
  @current_user
  @current_session

  def current_user
    @current_user = User.find(cookies[:user_id]) if(cookies[:user_id])
  end

  def current_session
    @current_session = Session.find_by_secret_key(cookies[:session_secret_key])
  end

  def current_user=(user)
    @current_user = user
  end

  def current_session=(session)
    @current_session = session
  end
end

and a controller:

class SessionsController < ApplicationController
  include SessionsHelper
  respond_to :json

  def create
    u = User.find_by_ip(request.remote_ip)
    u = User.create({:ip => request.remote_ip}) unless u

    s = Session.create
    s.admin = u
    s.save!

    send(:current_user=,u)
    send(:current_session=,s)

    respond_with s
  end
end

notice how I have to set the current user with the :send method, because calling current_user=u directly in the controller will not do it.

mabounassif
  • 2,311
  • 6
  • 29
  • 46

2 Answers2

0

I guess you're using devise. I don't see any question here, but maybe what you want to do is put the following in your application controller:

before_filter :load_current_user

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

@current_user will then be accessible in all your controllers.

yoones
  • 2,394
  • 1
  • 16
  • 20
0

Calling current_user directly is expected to work, however you need to use the self explicit receiver

def create
  u = User.find_by_ip(request.remote_ip)
  u = User.create({:ip => request.remote_ip}) unless u

  s = Session.create
  s.admin = u
  s.save!

  self.current_user = u
  self.current_session = s

  respond_with s
end

Otherwise, the following code will set a local method variable

def create
  u = User.find_by_ip(request.remote_ip)
  u = User.create({:ip => request.remote_ip}) unless u

  s = Session.create
  s.admin = u
  s.save!

  current_user = u
  current_session = s

  respond_with s
end

As a side note, you may want to use meaningful variable names.

def create
  user = User.find_by_ip(request.remote_ip) || User.create(:ip => request.remote_ip)

  session = Session.create
  session.admin = user
  session.save!

  self.current_user = user
  self.current_session = session

  respond_with session
end
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364