熱門文章

2016年10月17日 星期一

[Rails]AJAX筆記-使用內建方式

使用內建ajax的方法

  1. 在from_for 加入 remote:true
  2. 在controller的相對應action,加入format.js (create action)
  3. 新增相對應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 


將其改為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 for authenticity_token in forms with remote: true. By default it's set to false, which means that remote forms will not include authenticity_token, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the meta tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass authenticity_token: true as a form option or set this config setting to true.

沒有留言:

張貼留言