2015-10-15 58 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 –

相关问题