首页 > 解决方案 > 为什么我的表单身份验证辅助方法会导致整个提交输入类型从页面中删除?

问题描述

我编写了一个辅助方法,它将输出 HTML 以验证表单:

module ApplicationHelper
  def auth_token
    "<input type=\"hidden\" name=\"authenticity_token\" value=\"#{form_authenticity_token}\"".html_safe
  end
end

我尝试在 application.html.erb 的这部分 HTML 代码中使用它:

<% if logged_in? %>
    <p>Logged In</p>
    <form action="<%= session_url %>" method="POST">
      <input type="hidden" name="_method" value="DELETE">
      <%= auth_token %>
      <input type="submit" value="Logout">
    </form>
  <% else %>
    <p>Logged out</p>
    <form action="<%= new_session_url %>" method="GET">
      <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">
      <input type="submit" value="Login">
    </form> 
  <% end %>

我一次只测试一个按钮,所以目前只有注销按钮使用这个辅助方法!但是,一旦我登录,注销按钮就不会显示(但会出现段落文本)。当我明确地输入表单身份验证输入标签而不是使用我的辅助方法时,它就可以工作了。我仔细检查了我的辅助方法和 erb 标签,对我来说它看起来是正确的。关于为什么会发生这种情况的任何想法?

标签: ruby-on-rails

解决方案


>您的辅助方法中缺少,请>在字符串末尾添加。

module ApplicationHelper
  def auth_token
    "<input type=\"hidden\" name=\"authenticity_token\" value=\"#{form_authenticity_token}\">".html_safe
  end
end

推荐阅读