如何在rails上生成AuthenticityToken

mlz*_*boy 35 ruby-on-rails ruby-on-rails-3

我自己构建了表单标签,当我将表单发布到服务器时,它给了我一个InvalidAuthenticityToken错误,所以我想知道如何在当前情况下添加它:

<form accept-charset="UTF-8" action="/crops/update" method="post">
  <input id="crop_x" name="crop_x" size="30" type="text" /><br />
    <input id="crop_y" name="crop_y" size="30" type="text" /><br />
  <input id="crop_w" name="crop_w" size="30" type="text" /><br />
   <input id="crop_h" name="crop_h" size="30" type="text" /><br />
  <input id="crop" name="crop" type="submit" value="Crop!" />
</form>
Run Code Online (Sandbox Code Playgroud)

响应错误是:

ActionController::InvalidAuthenticityToken in CropsController#update 
ActionController::InvalidAuthenticityToken
Rails.root: /home/mlzboy/my/crop2
Application Trace | Framework Trace | Full Trace
Run Code Online (Sandbox Code Playgroud)

fli*_*ald 73

有一个调用的视图助手form_authenticity_token返回当前会话的真实性标记.

在view.html.erb中:

 <form action="/blah" method="POST">
   <input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">
   <input name="first_name" type="text">
 </form>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,也许更多的Rails惯用方式是```<%= hidden_​​field_tag:authenticity_token,form_authenticity_token%>``` (8认同)

d4r*_*rky 7

这个答案首先适用于谷歌中的rails形式令牌标签,以便为将来的谷歌搜索世代保持简单:只需使用token_tag,它是一个定义的帮助器ActionView::Helpers::UrlHelper,返回隐藏输入form_authenticity_token作为默认值.