Rails 4.如何为通过partial呈现的表单添加authenticity_token? [英] Rails 4. How to add authenticity_token to forms rendered via partial?
问题描述
在我的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/>
仍然可以发布信息并创建新记录......
在您的情况下,我们有两种方法可以做到: 手动将authenticity_token字段添加到表单中,如下所示: authenticity_token:true
在表单选项中
<%= 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:
Add
authenticity_token: true
in form optionsManually add authenticity_token field into form, like this:
<%= hidden_field_tag :authenticity_token, form_authenticity_token -%>
这篇关于Rails 4.如何为通过partial呈现的表单添加authenticity_token?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!