【问题标题】:Sinatra on Heroku: Can't set a session variable to nilHeroku 上的 Sinatra:无法将会话变量设置为 nil
【发布时间】:2012-01-22 05:50:11
【问题描述】:

我目前正在学习 Sinatra,但我似乎无法将会话变量设置为 nil...我一直在寻找几个小时,但它只是不起作用。奇怪的是它在我的机器上本地工作,但在 Heroku 上不起作用。简而言之,我的代码如下所示:

configure :production do
    enable :sessions
    set :session_secret, ENV['SESSION_KEY'] || 'whatever'
end

post '/send-operation/?' do
    session[:message] = 'Operation completed!'
    redirect '/operation/'
end

get '/operation/?' do
    if(session[:message])
        "The message is: #{session[:message]}."  
        session[:message] = nil
    end 
end

所以如果我调用“send-opration”路由,它会将我重定向到“operation”路由并显示 session[:message] 变量。如果我刷新“操作”页面,应该没有任何消息,因为上一条消息已设置为 nil。但它仍然显示“操作完成!”每次我调用“操作”路线。我是不是做错了什么?

感谢阅读!

【问题讨论】:

    标签: session heroku sinatra null unset


    【解决方案1】:

    您应该使用rack-flash 而不是直接使用会话来设置状态消息。每次请求后都会自动删除 flash 项目。

    在您的控制器中:

     flash[:error] = <your message>
    

    我的模板使用 HAML,所以它看起来像这样:

    - if !flash[:error].blank? then 
        %p{ :class => "error" }= flash[:error]              
    - if !flash[:notice].blank? then 
        %p{ :class => "notice" }= flash[:notice]
    

    希望有帮助!

    编辑:

    也可以看看sinatra-redirect-with-flash

    【讨论】:

    • 啊,对不起...我实际上并没有回答这个问题。 session[:message] = nil 在输出消息后被调用。所以它从来没有真正达到那个声明。
    猜你喜欢
    • 2014-03-02
    • 2011-08-03
    • 2011-11-13
    • 2021-12-23
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    相关资源
    最近更新 更多