Ruby on rails 如何在Rails 3中的cookie中存储登录用户名?
我想将登录用户名存储在2周左右到期的cookie中。我还希望登录视图从cookie中填充用户名。没有“记住我”复选框或任何必要的身份验证代码 根据下面的答案,以下是我使用的伪代码:Ruby on rails 如何在Rails 3中的cookie中存储登录用户名?,ruby-on-rails,ruby-on-rails-3,cookies,login,Ruby On Rails,Ruby On Rails 3,Cookies,Login,我想将登录用户名存储在2周左右到期的cookie中。我还希望登录视图从cookie中填充用户名。没有“记住我”复选框或任何必要的身份验证代码 根据下面的答案,以下是我使用的伪代码: # encoding: utf-8 class SessionsController < ApplicationController skip_before_filter :authorize def new params[:username] = cookies[:username] unl
# encoding: utf-8
class SessionsController < ApplicationController
skip_before_filter :authorize
def new
params[:username] = cookies[:username] unless cookies[:username].nil?
end
def create
if user
cookies[:username] = {:value => params[:username].downcase, :expires => 2.weeks.from_now }
end
end
end
编码:utf-8
类sessioncontroller为清晰起见,大部分代码已被省略。只需使用cookie存储设置cookie,如下所示:
cookies.signed[:username] = { :value => "username", :expires => 2.weeks.from_now }
<%= f.text_field :username, :value => cookies.signed[:username] %>
签名使cookie“防篡改”
在你看来,你可能会想要这样的东西:
cookies.signed[:username] = { :value => "username", :expires => 2.weeks.from_now }
<%= f.text_field :username, :value => cookies.signed[:username] %>
cookies.signed[:username]>
您想使用长表单设置cookie值,以便可以包括到期日期
cookies[:username] = { :value => "the_username", :expires => 2.weeks.from_now }
如果您希望使用带有
cookies的防篡改版本,则同样适用。签名[:用户名]
但该版本何时过期?它能在客户端持续两周吗?很抱歉我错过了那部分。我已更新我的答案以包含过期日期。那么如何在控制器或视图中使用它value=>cookies[:username]或:value=>cookies[:username][:value]?我上面代码中的:value
与视图中的:value
不同。使用上面的代码,您只需要:cookie[:username]>
,但在呈现视图之前,您最好在控制器中设置它:@user.username=cookie[:username]
。