在后端使用AngularJS和Rails刷新DIV

时间:2015-10-16 15:28:10

标签: javascript ruby-on-rails ruby angularjs

我使用'ng-click'使用AngularJS从我的数据库中删除帖子。

%table.table{"ng-controller" => "PostsCtrl"}
  %tr
    %th Title
    %th ....
    %th
  - @posts.each do |post|
    %tr
      %td...
      %td= link_to 'Delete', '', 'ng-click' => "deletePost('#{post.id}')", :id => "post_#{post.id}"

这是/app/views/posts/index.html.haml

它的行动:

 def index
   @posts = Post.all
 end

现在JS:

var app = angular.module('MyApp', ['ngResource']);
app.factory('Posts', function($resource){
 return $resource('/posts.json', {},{
    query: { method: 'GET', isArray: true },
    create: { method: 'POST' }
 })
});

app.factory('Post', function($resource) {
    return $resource("/posts/:id", { id: '@id' }, {
        'destroy': { method: 'DELETE', params: {id: '@id', responseType: 'json'} }
    });
});
app.controller("PostsCtrl", ['$scope', '$http', '$resource', 'Posts', 'Post', '$location', function($scope, $http, $resource, Posts, Post, $location) {

$scope.posts = Posts.query();
$scope.deletePost = function (post_id) {
    if (confirm("Are you sure you want to delete this user?")){
      Post.delete({ id: post_id }, function(){
        $scope.posts = Posts.query(); 

        $location.path('/');
        $scope.$apply();
      });
    }
  };
}]);

当我点击删除帖子的链接时,记录会从数据库中删除,但在JS控制台中会抛出以下错误信息:

DELETE http://localhost:3001/posts/5620a8766f85ce82ce000002 406 (Not Acceptable)

这是Rails行动:

  def destroy
    puts "test"
    respond_with @post.destroy!
  end

routes.rb

resources :posts do
  resources :comments
end

删除记录后如何摆脱错误并刷新表格?

提前谢谢。

修改

我刚刚发现,如果我点击链接删除相应的帖子,AngularJS会将请求作为HTML发送?从我在终端看到的情况来看:

Processing by PostsController#destroy as HTML
...
ActionController::UnknownFormat - ActionController::UnknownFormat:
...

1 个答案:

答案 0 :(得分:0)

正如您所说,406错误表示您的后端无法使用请求的格式(此处为HTML)进行响应。 一种可能的解决方案是在您的请求中指定json格式,如:

请注意.json

之后的:id
app.factory('Post', function($resource) {
    return $resource("/posts/:id.json", { id: '@id' }, {
        'destroy': { method: 'DELETE', params: {id: '@id', responseType: 'json'} }
    });
});