Rails 4.2 - 为belongs_to模型创建一个动作(Thinkster.io Angular + Rails教程)

时间:2015-02-03 03:33:59

标签: angularjs ruby-on-rails-4

我正在关注AngularJS + Rails教程https://thinkster.io/angular-rails/,并在最后的“完成评论”部分遇到了障碍(在它说“要启用添加评论后,我们可以使用”我们用于添加新帖子的相同技术“)。具体来说,当我点击/posts/{id}/comments.json端点时服务器正在抛出500。

我得到的错误是undefined local variable or method `post' for #<CommentsController:0x5f72b38>

post.rb:

class Post < ActiveRecord::Base
    has_many :comments

    def as_json(options = {})
        # Make all JSON representations of posts include the comments
        super(options.merge(include: :comments))
    end
end

comment.rb:

class Comment < ActiveRecord::Base
  belongs_to :post
end

postsCtrl.js:

angular.module('flapperNews')
.controller('PostsCtrl', [
    '$scope',
    'posts',
    'post',
    function($scope, posts, post) {
        $scope.post = post;

        $scope.addComment = function(){
          if($scope.body === '') { return; }
          posts.addComment(post.id, {
            body: $scope.body,
            author: 'user'
          }).success(function(comment) {
            $scope.post.comments.push(comment)
          });

          $scope.body = '';
        };
    }]);

posts.js:

angular.module('flapperNews')
.factory('posts', [
    '$http',
    function($http) {
        // Service Body
        var o = {
            posts: []
        };

        o.getAll = function() {
            return $http.get('/posts.json').success(function(data) {
                angular.copy(data, o.posts)
            });
        };

        o.create = function(post) {
            return $http.post('/posts.json', post).success(function(data) {
                o.posts.push(data);
            });
        };

        o.upvote = function(post) {
            return $http.put('/posts/' + post.id + '/upvote.json')
                .success(function(data) {
                    post.upvotes += 1;
                });
        }

        o.get = function(id) {
            return $http.get('/posts/' + id + '.json').then(function(res) {
                return res.data;
            });
        };

        o.addComment = function(id, comment) {
            return $http.post('/posts/' + id + '/comments.json', comment);
        }

        return o;
}]);

最后是comments_controller.rb:

class CommentsController < ApplicationController
    def create
        comment = post.comments.create(comment_params)
        respond_with post, comment
    end

    def upvote
        comment = post.comments.find(params[:id])
        comment.increment!(:upvotes)

        respond_with post, comment
    end

    private
    def comment_params
        params.require(:comment).permit(:body)
    end
end

我理解它在创建动作中引用了post的引用,但我不知道为什么Rails不只是将其识别为注释所属的帖子。我对Rails很新,但我看不到任何与教程有所不同的东西。非常感谢!

1 个答案:

答案 0 :(得分:1)

小男孩,我现在觉得自己很傻。我在创建操作的顶部添加了以下行,它现在可以正常工作:post = Post.find(params[:post_id])希望这可以帮助其他任何被卡住的人!该教程似乎缺少这一部分。