2012-01-29 27 views
1

試圖在jQuery UI對話框中實現窗體。我有一個模型「客戶」,標準操作新,創建更新等。Rails Ajax .post請求未運行,因爲它應該

對於「新客戶」鏈接我有一個代碼,將表單加載到模式,然後允許我通過表單提交一個帖子請求。 對話框裏面我有幾個按鈕提交表單

buttons: {"Save": function() {  
     $.post("/customers", $("#new_customer").serializeArray()); 
     $(this).dialog('close');}, 
       "Cancel": function() {$(this).dialog('close');} 
    }  

這工作得很好。

但是,當我嘗試複製編輯鏈接時,它不起作用。

buttons: {"Save": function() {  
     $.post("/customers", $("#edit_customer").serializeArray()); 
     $(this).dialog('close');}, 
       "Cancel": function() {$(this).dialog('close');} 
    }  

我看耙路線在它說:

customers GET /customers(.:format) {:action=>"index", :controller=>"customers"} 
      POST /customers(.:format) {:action=>"create", :controller=>"customers"} 

所以,這是因爲編輯不起作用?我是否需要爲它創建一個命名路線?請讓我知道你認爲可能是什麼問題!

我的創建方法如下:

def create 
    @customer = Customer.new(params[:customer]) 
    if @customer.save 
     redirect_to @customer, :notice => "Successfully created customer." 
    else 
     render :action => 'new' 
    end 
    end 

在routes.rb中我有:

resources :customers do 
    resources :plans 
    end 

和產生的途徑有:

 customers GET /customers(.:format)        {:action=>"index", :controller=>"customers"} 
        POST /customers(.:format)        {:action=>"create", :controller=>"customers"} 
    new_customer GET /customers/new(.:format)       {:action=>"new", :controller=>"customers"} 
    edit_customer GET /customers/:id/edit(.:format)     {:action=>"edit", :controller=>"customers"} 
     customer GET /customers/:id(.:format)       {:action=>"show", :controller=>"customers"} 
        PUT /customers/:id(.:format)       {:action=>"update", :controller=>"customers"} 

我有一個部分與我加載的新形式和編輯方法(相同的部分)。

<%= form_for @customer do |f| %> 
... 
<% end %> 

,但在源代碼中,它說:

<form accept-charset="UTF-8" action="/customers/1" class="edit_customer" id="edit_customer_1" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="put"><input name="authenticity_token" type="hidden" value="DpfK5tChAxY3gOT8CfKQQTS6igRUMAM4tQbCf3GeA8I="></div> 

那麼如何我使用JS的PUT?

謝謝!

+0

在編輯的情況下嘗試用'$改變'$ .post'。得到' – Rafay 2012-01-29 19:37:22

+0

它什麼都不做,它在服務器上呈現,但不編輯對象。 – Lievcin 2012-01-29 19:42:45

+0

但是POST運行'create';這與'update'不同,不是嗎?你的'create'方法是什麼樣的? – 2012-01-29 19:45:16

回答

0

如果定義爲REST資源的客戶:

resources :customers 

再就是爲您的休息控制器定義了兩個動作

GET /customers/:id/edit(.:format) {:action=>"edit", :controller=>"users"} 
PUT /customers/:id(.:format) {:action=>"update", :controller=>"users"} 

所以儘量$不用彷徨,而不是$。員額,如果你想加載客戶表單和POST(PUT)進行更新。 由於瀏覽器不支持PUT方法好時,Rails通過POST請求模擬這一點,但將隱藏到像<input name="_method" type="hidden" value="put"> 形式您不必如果您創建表單軌辦法做到這一點,

form_for(@customer) do |form| ... 

然後,如果你編輯現有的客戶,這個標籤會自動插入,所以如果你序列化,它會在那裏。

如果您沒有REST資源,那麼您缺少路由。你會得到什麼錯誤?

+0

我該怎麼做你建議的POST(帶隱藏的PUT)? – Lievcin 2012-01-29 19:56:08

+0

我更新了上面的答案。 – Johny 2012-01-29 20:09:38

+0

感謝Johny,但我有點失落。我再次編輯了這個問題,因爲現在格式化會出錯。 – Lievcin 2012-01-29 20:36:09