开发者

How to access session variables across multiple controllers in Rails?

I have implemented a facebook connect for my application. So when a user logs in I wish to store his facebook id in the session and use it across multiple controllers and views. I tried implementing this . I also referred to several similar questions answered in stackoverflow . However something seems wrong. I set the facebook id in the session in the UserController . I am not able to access it in the EventsController.

The flow is : When the user logins in for the first time . The fbinsertupdate is called. And then the page redirects to events#index page.

class User < ActiveRecord::Base

 def self.current=(u)
@current_user = u
end

def self.current
@current_user
end


end





class ApplicationController < ActionController::Base
  protect_from_forgery



  # Finds the User with the ID stored in the session with the key
  # :fb_user_id 

  def current_user
    User.current  ||= session[:fb_user_id] &&
      User.find(sessio开发者_C百科n[:fb_user_id])
  end


end




class UsersController < ApplicationController



  def fbinsertupdate  #Facebook connect. Insert new user or update existing user


    @user = User.find_or_create_by_fbid(params[:fbid]) 
    @user.update_attributes(params[:user])
    session[:fb_user_id] = @user.fbid  # storing the facebook id in the session
    render :nothing => true




  end



end


class EventsController < ApplicationController

  def index
     @events = Event.all
     @current_user= User.current
    logger.debug "The current user is  "+@current_user.name  # This fails . Says the class in nil

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @events }
    end
  end


end


Is there a before_filter missing? You do not seem to call the current_user method at all (that reads the session). I see two ways to correct this:

Either use a before_filter: at the top of your EventsController write

class EventsController < ApplicationController

  before_filter :current_user 

  def index
    @events = Event.all
    @current_user= User.current
    logger.debug "The current user is  "+@current_user.name  # This fails . Says the class in nil

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @events }
    end
  end
end

or, you change your index-code as follows:

  def index
    @events = Event.all
    @current_user= current_user
    logger.debug "The current user is  "+@current_user.name  # This fails . Says the class in nil

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @events }
    end
  end

Note that if you are using an API, using rest/soap, that there is no session and that you will have to return information (e.g. xml or json), that then could be handed along in the next call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜