Rails 4.如何为通过partial呈现的表单添加authenticity_token? [英] Rails 4. How to add authenticity_token to forms rendered via partial?

查看:242
本文介绍了Rails 4.如何为通过partial呈现的表单添加authenticity_token?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的rails应用程序中,在所有页面上,在head部分有这2个meta标签:

 < meta name =csrf-paramcontent =authenticity_token/> 
< meta name =csrf-tokencontent =027GUZBeEkmv .../>

在不使用局部呈现的表单上,隐藏 authenticity_token b

$ p $ < input type =hiddenname =authenticity_tokenvalue =D5TddQruJppDD3 ... />

但是如果我只是像这样载入表单,这个字段就会丢失:

 <%= render'shared / comment_form'%> 

这是预期的行为吗?我应该手动添加一个 authenticity_token ,如果是的话,我该如何验证它?

编辑 strong>



共享/ _comment_form.html.erb

 <%= form_for([@ post,@comment],:html => {:onsubmit =>validateCommentForm(event)},remote:true)do | f | %GT; 
<%= render'shared / error_messages',object:f.object%>
< div class =field>
<%= f.text_area:content,placeholder:添加到文章中,使其更加%>
< / div>

<%= f.submitSave,class:btn btn-info%>
<%end%>

另外,添加< input type =hiddenname =authenticity_token id =authenticity_tokenvalue =ANYING/> 仍然可以发布信息并创建新记录......

h2_lin>解决方案

在您的情况下,我们有两种方法可以做到: authenticity_token:true 在表单选项中

  • 手动将authenticity_token字段添加到表单中,如下所示:


  • <%= hidden_​​field_tag:authenticity_token,form_authenticity_token - %>

    On my rails app, on all pages, in the head section there are these 2 meta tags:

    <meta name="csrf-param" content="authenticity_token" />
    <meta name="csrf-token" content="027GUZBeEkmv..." />
    

    On forms not rendered using a partial there is a hidden authenticity_token field

    <input type="hidden" name="authenticity_token" value="D5TddQruJppDD3..." />
    

    But this field misses if I simply load the form like this:

    <%= render 'shared/comment_form' %>
    

    Is this expected behavior ? Should I manually add an authenticity_token and if so how do I validate it ?

    Edit:

    shared/_comment_form.html.erb

    <%= form_for([@post, @comment], :html => { :onsubmit => "validateCommentForm(event)" }, remote:true) do |f| %>
        <%= render 'shared/error_messages', object: f.object %>
        <div class="field">
            <%= f.text_area :content, placeholder: "Add to the article. Make it be more" %>
        </div>
    
        <%= f.submit "Save", class: "btn btn-info" %>
    <% end %>
    

    Also, adding <input type="hidden" name="authenticity_token" id="authenticity_token" value="ANYTHING" /> to that form still manages to post the info and create a new record...

    解决方案

    In your case, we have two ways to do:

    1. Add authenticity_token: true in form options

    2. Manually add authenticity_token field into form, like this:

    <%= hidden_field_tag :authenticity_token, form_authenticity_token -%>

    这篇关于Rails 4.如何为通过partial呈现的表单添加authenticity_token?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆