2016-03-15 69 views
6

在我的Rails應用程序,在所有頁面,在頭節還有這2個meta標籤:Rails 4.如何爲通過partial呈現的表單添加authenticity_token?

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

在窗體中使用的部分有一個隱藏的authenticity_token場不會呈現

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

但如果我簡單地加載這樣的表單,這個字段會丟失:

<%= render 'shared/comment_form' %> 

這是預期的行爲嗎?我應該手動添加一個authenticity_token,如果有的話,我如何驗證它?

編輯:

共享/ _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 %> 

而且,加入<input type="hidden" name="authenticity_token" id="authenticity_token" value="ANYTHING" />這種形式仍然設法發佈的信息並創建一個新的記錄...

+0

時稱爲例如可以具有部分發送當地人: <%= render'shared/comment_form,:當地人=> {:令牌=> 'kasdlfjasldfj'}% – bkunzi01

+0

的'form_for'助洗劑或'的form_tag '通常需要添加帶有真實性標記的隱藏字段,你能告訴我們'shared/comment_form'的形式嗎? – sled

回答

25

在你的情況,我們有兩種方法可以做到:

  1. 添加authenticity_token: true形式選項

  2. 手動添加authenticity_token場到形式,這樣:

<%= hidden_field_tag :authenticity_token, form_authenticity_token -%>

+0

是的,這是解決方案,但解釋發生了什麼是理解這種情況的原因所必須的,我在下面的答案中加入了 – Catalin

2

好的,所以它似乎是關於遠程表單,而不是通過部分加載的表單:

將config.action_view.embed_authenticity_token_in_remote_forms的默認值更改爲false。這種改變打破了在沒有JavaScript的情況下也需要工作的遠程表單,所以如果你需要這樣的行爲,你可以將其設置爲true或者在表單選項中顯式傳遞authenticity_token:true。

找到答案在這裏:https://github.com/rails/rails/issues/10608