2015-10-15 57 views
0

我堅持了整整一天。Rails + Angularjs:如何與後端進行通信(從數據庫刪除記錄)?

http://localhost:3001/posts/,我列出了我在數據庫中的所有帖子。我試圖刪除任務使用Angularjs - 從數據庫中每一個加載的記錄有其刪除鏈接:

= link_to 'Delete', '', 'ng-click' => "deletePost('#{post.id}')", :id => "post_#{post.id}" 

然後,我有一個文件/assets/javascript/angular/controller/posts.js看起來像這樣:

var app = angular.module('AngTestApp', ['ngResource']); 

app.factory('Post', function($resource) { 
    return $resource("/posts/:id", { id: '@id' }, { 
     index: { method: 'GET', isArray: true, responseType: 'json' }, 
     show: { method: 'GET', responseType: 'json' }, 
     update: { method: 'PUT', responseType: 'json' } 
    }); 
}) 

app.controller("PostsCtrl", function($scope, Post) { 
    $scope.posts = Post.index(); 
    $scope.deletePost = function(index) { 
     console.log("index: "+index); 
     post = $scope.posts[index]; 
     Post.delete(post); 
     $scope.posts.splice(index, 1); 
     console.log('aa'); 
    } 
}) 

當我點擊刪除鏈接,我收到此錯誤的JS控制檯:

DELETE http://localhost:3001/posts 404 (Not Found) 

和終端:

Started DELETE "/posts" for 127.0.0.1 at 2015-10-15 16:23:08 -0700 

ActionController::RoutingError (No route matches [DELETE] "/posts"): 

的路線是這樣的:

resources :posts do 
    resources :comments 
end 

JS代碼非常混亂,我試圖修改教程中,我在網上找到的,但它不能很好地工作。

這種嘗試有什麼問題?

預先感謝您。

回答

1

您需要將您試圖刪除的記錄的ID作爲參數傳遞給Rails。 Rails告訴你它找不到路由,因爲你沒有ID。

由於您沒有在您的工廠中定義DELETE操作,因此可能爲什麼ID沒有通過。您也可以嘗試明確地傳遞ID作爲PARAM,如下圖所示: $資源需要PARAMS屬性,這樣你就可以修改你的工廠,像這樣:

app.factory('Post', function($resource) { 
    return $resource("/posts/:id", { id: '@id' }, { 
     index: { method: 'GET', isArray: true, responseType: 'json' }, 
     show: { method: 'GET', responseType: 'json' }, 
     update: { method: 'PUT', responseType: 'json' }, 
     delete: { method: 'DELETE', params: '@id', responseType: 'json' } 
    }); 
}) 

的$資源文檔是非常有益的:https://docs.angularjs.org/api/ngResource/service/ $資源

+0

嗨布拉德,感謝您的回答。我試過,但結果是TypeError:無法在JS控制檯中讀取'undefined'的屬性'delete'。我是否需要在項目中加入一些圖書館? – user984621

+0

嗯,似乎有一個類型的地方,工廠正在返回undefined。你也可以看看這個:https://stackoverflow.com/questions/16167463/angular-js-delete-resource-with-parameter –

相關問題