Gem grape cookies 问题

naitnix · May 23, 2012 · Last by naitnix replied at May 24, 2012 · 3319 hits

今天遇到这么一个问题: 在 api.rb 文件内 get 'login' do user = User.authenticate(params[:mobile], params[:password]) if user.present? cookies[:auth_token] = user.auth_token end Rails.logger.info("***********************") Rails.logger.info(cookies[:auth_token]) Rails.logger.info("***********************")
end

以上是一个发送 get 请求的登录的 api,即每次登录,如果在数据库里面查到该用户的时候,就将该用户的 token 存储到 cookies 里面,然后紧接着我就打印了下这个 cookies,看看有没有存储成功,然后我在请求之后查看 log,发现 cookies 里面是有这个 token 的字符串的,ok,这说明 cookies 存储成功了。

接下来,我在 helper 文件 (helpers.rb) 里面写了一个方法: def current_user if cookies[:auth_token].present? @current_user = User.find_by_auth_token(cookies[:auth_token]) else @current_user = nil end end

即每次调用 current_user 方法的时候,都根据 cookies 里面的 token 去查找该用户

然后我在 api.rb 里面: require "api/helpers" helpers APIHelpers 即引入了 helpers.rb,并且将里面的所有方法声明为 helper 方法,这样可以在 api 里面随意调用。

当我调用当前用户的数据的时候,发现请求到 current_user 的时候,cookies 里面的值不见了:

get 'favourite' do @stores = current_user.stores.order("id desc").page(params[:page]).per(page_size) end

这个时候报错了,说是请求 current_user 的时候返回的 user 为空,这我就郁闷了,难道是在 helper 里面不能调用 cookies 么?于是乎我就打印了下 cookies:

def current_user Rails.logger.info("***********************") Rails.logger.info(cookies[:auth_token]) Rails.logger.info("***********************")
if cookies[:auth_token].present? @current_user = User.find_by_auth_token(cookies[:auth_token]) else @current_user = nil end end

晕,cookies 果真为空,不知道为啥了,难道是 cookies 不能在 helper 里面访问么?

楼主能把代码好好贴么。。看起来费劲

没记错的话,cookie 是写了后要下次访问才能拿到的。

cookies 在存储了后下次才能访问这个是没错的,但是你看见我的代码了么,在存储完了以后,直接 log 出来了,这说明我存储完了,紧接着去调用 cookies 是可以的。而且我的应用情况是,先登录,等录完后,我访问的是另一个 url 了,这明显是第二次或者地 n 次请求了,在 helper 里面依然没法拿到 cookies

You need to Sign in before reply, if you don't have an account, please Sign up first.