2

I'm an Angular newb and am trying to POST a nested resource to my Rails backend with Angular. I'm working with two models: posts and comments. A post has_many comments. I'm rendering my comments with my posts via "includes" in my PostsController.

I can create new posts through my browser with angular; however I can't for the life of me figure out how to create new comments. I get this error in the js console when trying to enter a comment:

POST http://localhost:3000/posts/1/comments 400 (Bad Request) angular.js?body=1:9313

I get these errors in my rails console:

Started POST "/posts/1/comments" for 127.0.0.1 at 2013-09-02 18:41:24 -0700
Processing by CommentsController#create as JSON
  Parameters: {"post_id"=>"1"}
Completed 400 Bad Request in 1ms

ActionController::ParameterMissing (param not found: comment):
  app/controllers/comments_controller.rb:34:in `comment_params'
  app/controllers/comments_controller.rb:12:in `create' 

I've tried several different methods and tried to duplicate the logic in this post (Angular JS ngResource with nested resources) but to no avail.

Here's my factories:

factoriesModule.factory "Post", ["$resource", ($resource) ->
  $resource("/posts/:id", {id: "@id"},{
  update: {method: "PUT"}
})
]

factoriesModule.factory "Comment", ["$resource", ($resource) ->
  $resource("/posts/:post_id/comments/:id", {id: "@id", post_id: "@post_id"},
  update: {method: "PUT"}
)
]

Here's my controllers:

@PostingCtrl = ["$scope", "Post", ($scope, Post) ->
$scope.posts = Post.query()

$scope.addPost = ->
post = Post.save($scope.newPost)
$scope.posts.push(post)
$scope.newPost = {}
]

@CommentingCtrl = ["$scope", "Comment", "$http", ($scope, Comment, $http) ->
 $scope.comments = Comment.query({post_id: @post_id, id: @id})

$scope.addComment = (post_id, data) ->
  console.log $scope.newComment.text
$http.post("/posts/" + post_id + "/comments", data).success alert 'hi' 
]

I'm using the $http service for addComment as that's the only way I've found that gives my comment the post_id (gotten in with my view logic). Apologies for the lengthy post and thank you very much for any help!

Community
  • 1
  • 1
Brian Schroer
  • 33
  • 2
  • 5
  • It may be that I don't see all of the code/html here, but based on your controller error it appears that you don't have a param["comment"] coming across. From your addComment method I can't see who is calling that. I assume it's called from an html page i.e., ng-submit="addComment()". If true then you need to make sure your fields are prefixed with "comment." otherwise the params will be "flat" coming across to the server. – Arthur Frankel Sep 03 '13 at 02:15
  • [enter link description here](http://stackoverflow.com/questions/16549382/how-to-permit-an-array-with-strong-parameters) This problem is not related to AngularJS. – 51ch Apr 11 '16 at 13:18

0 Answers0