设置和识别cookie何时为零

时间:2018-01-06 13:26:22

标签: ruby-on-rails cookies

我有一个小但很烦人的错误。

<%=link_to "Home", controller: "homepage", action: "index"%>
<%if cookies[:session] == nil %>
<%=link_to "Sign Up", controller: "accounts", action: "new"%>
<%=link_to "Log in", controller: "accounts", action: "login"%>
<%end%>  
<%if cookies[:session] != nil%>
<%=link_to "Account", controller: "accounts", action: "show", id: cookies[:session]%>
<%=link_to "Sign out", controller: "accounts", action: "signout"%>
<%end%>

这是导航栏。它应该检查一个帐户是否已经登录。如果有,它将显示帐户和注册链接,如果它没有值,它将显示注册并登录。 链接。

def create
    @account = Account.new(account_params)
    if @account.save
      cookies[:session] = @account[:id]
      redirect_to action: 'show', id: @account[:id]
    else
      render 'new'
    end
  end

 def verify
    @checkaccount = account_params
    account = Account.find_by_username(@checkaccount[:username])
    if account != nil
      cookies[:session] = "test"
      if account[:password] == @checkaccount[:password]
        cookies[:session] = account[:id]
      end
      redirect_to action: 'show', id: account[:id]
    else
      redirect_to action: 'show', id: account[:id]
    end
  end

def signout
    cookies[:session] = nil
    redirect_to controller: 'homepage', action: 'index'
  end

这是我的代码,用于识别帐户登录或退出的时间。当一个帐户退出时,存储其会话值的cookie应为零,但导航栏仍会显示“帐户”和“注销”按钮,就好像该值不是零一样。

1 个答案:

答案 0 :(得分:0)

如果您将Cookie值设置为nil,则会将其作为空字符串""存储在浏览器中,而不是nilnull。因此,您需要使用presentblank,而不是检查值为nil

<%=link_to "Home", controller: "homepage", action: "index"%>

<% if cookies[:session].present? %>
  <%=link_to "Account", controller: "accounts", action: "show", id: cookies[:session]%>
  <%=link_to "Sign out", controller: "accounts", action: "signout"%>
<% else %>
  <%=link_to "Sign Up", controller: "accounts", action: "new"%>
  <%=link_to "Log in", controller: "accounts", action: "login"%>
<% end %>