熱門文章

顯示具有 form_for 標籤的文章。 顯示所有文章
顯示具有 form_for 標籤的文章。 顯示所有文章

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.

2016年8月15日 星期一

[rails]form-tag

>>index.html.erb

<%= form_tag(groups_path, method: "get") do %>
  <%= label_tag(:q) %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("搜索") %>
<% end %>
<%= @a %>
</div>


groups_path  :處理的路徑
:q 將被存在 controller 裡相對路徑的 method 裡
此範例是 groupscontroller.rb的 index 裡如下

def index
@groups = Group.all
a = params[:q]
end

對網頁應用程式來說,表單是非常重要的用戶輸入介面。Rails在這方面也提供了很多好用的Helper方法。基本上,Rails處理表單分成兩種類型:
一種是對應到Model物件的新增、修改,我們會使用form_for這個Helper。它的好處在於透過傳入Model物件,可以在修改的時候自動幫你將預設值帶入。例如我們已經在Part1使用過的event表單:
<%= form_for @event do |f| %>
    <%= f.text_field :name %>
    <%= f.submit %>
<% end %>
另一種是就是沒有對應Model的表單,我們使用form_tag這個方法。例如:
<%= form_tag "/search" do %>
    <%= text_field_tag :keyword %>
    <%= submit_tag %>
<% end %>
和form_for有些類似,但是其中不需要傳Block變數f,其中的欄位Helper需要多加_tag結尾。不像form_for的欄位名稱一定要是Model的屬性之一,在form_tag之中的欄位名稱則完全不受限。


form_tag 是啥?跟 form_for 有什麼不一樣?

Adler @ 2015-07-18