I am using `ng-click' in AngularJS to delete a post from my database.
%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}"
This code snippet is located in /app/views/posts/index.html.haml
.
Here's the action for deleting a post:
def index
@posts = Post.all
end
And here is the corresponding JavaScript code:
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();
});
}
};
}]);
Although the record is successfully deleted from the database when I click the delete link, an error message appears in the JS console:
DELETE http://localhost:3001/posts/5620a8766f85ce82ce000002 406 (Not Acceptable)
Below is the Rails action associated with deletion:
def destroy
puts "test"
respond_with @post.destroy!
end
And here are the routes defined in routes.rb
:
resources :posts do
resources :comments
end
How can I resolve this error and refresh the table after deleting a record?
Thank you for your assistance.
EDIT:
Upon further investigation, it appears that AngularJS is sending the request as HTML when attempting to delete a post. This is evident from the output in the terminal:
Processing by PostsController#destroy as HTML
...
ActionController::UnknownFormat - ActionController::UnknownFormat:
...