2011-12-29 35 views
1

擁有2個模型customer和comm_log。它們的關聯如下:如何在rails 3.1中的link_to中構造刪除路由?

resources :customers do 
    comm_logs 
end 

在comm_logs控制器中銷燬的rspec代碼沒有任何錯誤地傳遞。 lambda模塊驗證成功刪除後,通訊記錄數減1。控制器中的一切看起來都是正確

耙路線的輸出是:

 new_customer_comm_log GET /customers/:customer_id/comm_logs/new(.:format)     {:action=>"new", :controller=>"comm_logs"} 
     edit_customer_comm_log GET /customers/:customer_id/comm_logs/:id/edit(.:format)   {:action=>"edit", :controller=>"comm_logs"} 
      customer_comm_log GET /customers/:customer_id/comm_logs/:id(.:format)     {:action=>"show", :controller=>"comm_logs"} 
          PUT /customers/:customer_id/comm_logs/:id(.:format)     {:action=>"update", :controller=>"comm_logs"} 
          DELETE /customers/:customer_id/comm_logs/:id(.:format)     {:action=>"destroy", :controller=>"comm_logs"} 

在現實中,記錄不點擊刪除按鈕後刪除,因爲它是在控制器(顯示頁面的頁面沒有重定向到前一頁只是保持不變,刪除後沒有重定向到任何地方)。看來,刪除操作被路由到了正確的路徑。問題很可能是以下視圖中的link_to:

<%= link_to 'delete', customer_comm_log_path(@customer, @comm_log), :method => :delete, :confirm => "are you sure?", :remote => true %> 

link_to上面有什麼問題嗎?謝謝。

+0

你可以發佈你的控制器銷燬方法嗎? – andrewpthorp 2011-12-29 18:23:42

回答

1

有幾件事你可能會錯過。我假設你使用jQuery,因爲你沒有在你的問題中指定。

一)請確保您有jQuery的安裝

二)確保已手動安裝了Rails UJS(不顯眼的JavaScript)的適配器或使用寶石(爲Rails 3.1說明這個鏈接以及): https://github.com/rails/jquery-ujs

C)你link_to需要告訴Rails的UJS適配器,它應該抓住該鏈接的點擊,並通過AJAX

<%= link_to 'delete', customer_comm_log_path(@customer, @comm_log), :remote => true, :method => :delete) %> 

所以提交DELETE請求在上面的link_to,你失蹤:remote => true

Rails會捕獲鏈路上的用戶的點擊,然後揭開序幕一個jQuery $.ajax呼叫到您的服務器,其中包括一對夫婦PARAMS告訴Rails的服務器,這是一個遠程DELETE請求。

d)如果您通過用戶單擊類似的遠程鏈接重定向到控制器,您需要通過將此代碼放置在您的ApplicationController中來告訴Rails正確處理AJAX重定向。如果你不這樣做,鏈接將刪除記錄,但它只會坐在那裏,而不是重定向。

# Allows redirecting for AJAX calls as well as normal calls 
    def redirect_to(options = {}, response_status = {}) 
    if request.xhr? 
     render(:update) {|page| page.redirect_to(options)} 
    else 
     super(options, response_status) 
    end 
    end 
+0

我正在運行rails 3.1.0,jquery似乎已經安裝。 Gemfile中有gem'jquery-rail'。在application.js中,需要jquery並且需要jquery.ui。剛剛添加jquery.ujs。在post中添加了def代碼,以便將ajax重定向到application_controller.rb。除了:remote => true,還添加了:confirm => true的link_to。點擊刪除時沒有啓動確認。沒有重定向。記錄仍然存在。 – user938363 2011-12-29 19:04:13

+0

服務器日誌說什麼(即請求曾經觸及服務器)?此外,請檢查您的瀏覽器的控制檯的JavaScript錯誤。如果你有JS錯誤,那麼它不會執行'$ .ajax'調用。 – iwasrobbed 2011-12-30 00:59:54

+0

創建new.js.erb文件並在lease_logs控制器中添加了帶有html和js格式的respond_to後,上面發佈的ajax destroy開始工作。 new.js.erb中有兩行:$(「<%= escape_javascript render(:file =>'lease_logs/new.html.erb')%>」)。insertAfter( '#new_log_link'); $('#new_log_link')。hide(); – user938363 2012-01-03 17:29:33