- 在from_for 加入 remote:true
- 在controller的相對應action,加入format.js (create action)
- 新增相對應action的js擋( create.js.erb)
when there is a file field in a form is submitted via AJAX.
在使用Ajax時,如果form裡面有file_field遇到問題
ActionController::InvalidAuthenticityToken error.
ActionController::InvalidAuthenticityToken in StoresController#create
Avoiding ActionController::InvalidAuthenticityToken on AJAX calls
Missing Authenticity Token in Remote Forms w/ File Upload Field(s) #22807
解決方法一:在form_for 加入 :authenticity_token => true
可以成功執行Create Action,但是不會以Ajax的方式執行
<%= form_for @some_model, :remote => true, :authenticity_token => true do |f| %>
<% end %>
解決方法二:
當form_for 改為 :remote=>true時 ,form 將不會包含 authenticity_token
因為以下預設值為false
config.action_view.embed_authenticity_token_in_remote_forms = false
因為以下預設值為false
config.action_view.embed_authenticity_token_in_remote_forms = false
將其改為true即可修正錯誤
config.action_view.embed_authenticity_token_in_remote_forms = true
官方解釋
config.action_view.embed_authenticity_token_in_remote_forms
allows you to set the default behavior forauthenticity_token
in forms withremote: true
. By default it's set tofalse
, which means that remote forms will not includeauthenticity_token
, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from themeta
tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either passauthenticity_token: true
as a form option or set this config setting totrue
.
沒有留言:
張貼留言