我为我的应用程序实现了facebook连接。因此,当用户登录时,我希望将他的facebook id存储在会话中,并在多个控制器和视图中使用它。我试着实现这个。我还提到了stackoverflow中回答的几个类似的问题。但似乎有些不对劲。我在UserController中的会话中设置了facebook id。我无法在EventsController中访问它。
流程是:当用户第一次登录时。调用fbinsertupdate。然后页面重定向到事件#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(session[: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
答案 0 :(得分:1)
是否遗失了before_filter
?您似乎根本没有调用current_user
方法(读取会话)。我认为有两种方法可以解决这个问题:
在before_filter
写
EventsController
:
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
或者,您更改了index
- 代码,如下所示:
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
请注意,如果您正在使用API,使用rest / soap,那么没有会话,并且您必须返回信息(例如xml或json),然后可以在下一次调用中将其传递。