【问题标题】:Rails: Completed 500 Internal Server Error, with AngularJS $http.post callRails:使用 AngularJS $http.post 调用完成 500 内部服务器错误
【发布时间】:2015-02-15 07:50:51
【问题描述】:

我目前正在编写本教程:AngularJS Tutorial: Learn to Build Modern Web Apps with Angular and Rails

在教程项目中,用户可以为这些帖子创建博客帖子评论。到目前为止,我已经能够创建博客 Posts(保存到数据库中),但是当我尝试为 Post 创建 Comment >,然后我得到以下错误

Started POST "/posts/16/comments.json" for 127.0.0.1 at 2015-02-15 08:32:40 +0200
Processing by CommentsController#create as JSON
  Parameters: {"body"=>"6", "author"=>"user", "post_id"=>"16", "comment"=>{"body"=>"6"}}
Comments create action entered... 6
Completed 500 Internal Server Error in 9ms

NameError (undefined local variable or method `post' for #<CommentsController:0xb6036e50>):
  app/controllers/comments_controller.rb:6:in `create'

注意:行 “评论创建动作输入... 6 ”logger.info 消息。

截图

cmets_controller.rb

class CommentsController < ApplicationController

  def create
        logger.info "Comments create action entered... " + params[:body]

    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

posts_controller.rb

class PostsController < ApplicationController

  def index
    respond_with Post.all
  end

  def create
    respond_with Post.create(post_params)
  end

  def show
       logger.info "show action entered... " + params[:id]

    #respond_with Post.find(params[:id])
    #the code below works,  the line above resulted in error: 406 (Not Acceptable)
    render json: Post.find(params[:id]).to_json 
  end

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

    respond_with post
  end

  private

  def post_params
    logger.info "post_params entered..."
    params.require(:post).permit(:link, :title)
  end
end

PostsControllershow 操作中,我之前已将行:respond_with Post.find(params[:id]) 更改为:render json: Post.find(params[:id]).to_json,因为行:respond_with Post.find(params[:id]) 产生错误:GET http://0.0.0.0:3000/posts/4 406 (Not Acceptable)

我不确定,但上述问题可能与 internal error (500) 消息有关,为什么找不到帖子。此外,如果我在 PostsController 中使用 line: respond_with Post.find(params[:id]) ,那么创建 Comment 时我仍然会遇到同样的问题。

application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  respond_to :json

  def angular
    render 'layouts/application'
  end
end

routes.rb

FlapperNews::Application.routes.draw do

  root to: 'application#angular'

  resources :posts, only: [:create, :index, :show] do
    resources :comments, only: [:show, :create] do
      member do
        put '/upvote' => 'comments#upvote'
      end
    end

    member do
      put '/upvote' => 'posts#upvote'
    end
  end
end

下面是执行 Ajax 调用的 post.js 文件,其中o.addComment 函数的$http.post 调用尝试以下列方式创建评论:$http.post('/posts/' + id + '/comments.json', comment);

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

     o.getAll = function() {
            return $http.get('/posts.json').success(function(data){
                angular.copy(data, o.posts);
            });
        };
        o.create = function(post) {
            console.log("o.create");
            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).then(function(res){
            return res.data;
          });
        };
        o.addComment = function(id, comment) {
            console.log("addComment " + id + ", comments " + comment )
          return $http.post('/posts/' + id + '/comments.json', comment);
        };
        o.upvoteComment = function(post, comment) {
            console.log("o.upvoteComment " + post.id + ", comments " +comment.id)
          return $http.put('/posts/' + post.id + '/comments/'+ comment.id + '/upvote.json')
            .success(function(data){
              comment.upvotes += 1;
            });
        };
        return o; 
    }
]);

app.js

angular.module('flapperNews', ['ui.router', 'templates'])
.config([
  '$stateProvider',
  '$urlRouterProvider',
  function($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('home', {
        url: '/home',
        templateUrl: 'home/_home.html',
        controller: 'MainCtrl',
        resolve: {
          postPromise: ['posts', function(posts){
            return posts.getAll();
          }]
        }
      })
      .state('posts', {
        url: '/posts/{id}',
        templateUrl: 'posts/_posts.html',
        controller: 'PostsCtrl',
        resolve: {
          post: ['$stateParams', 'posts', function($stateParams, posts) {
            console.log( "$stateParams.id " +$stateParams.id)
            return posts.get($stateParams.id);
          }]
        }

      })
    $urlRouterProvider.otherwise('home')
}]);

我的 rails 版本是 4.0.2

任何帮助都将不胜感激,因为我已经在代码上苦苦挣扎了几个小时 :-) 无论如何,我很高兴有 Stackoverflow 论坛,在那里人们可以提出一些建议 :-)

【问题讨论】:

  • 你的comments_controllerpost 似乎是未定义的。在拨打post之前尝试添加post = Post.find(params[:id])

标签: ruby-on-rails ajax angularjs ruby-on-rails-4


【解决方案1】:

首先,这与角度无关。你没有定义帖子,所以添加:

post = Post.find params[:post_id]

另外,我认为你的评论属于帖子,你应该在保存评论之前将帖子设置为评论的帖子,所以:

@comment.post = post

【讨论】:

  • 太好了,我终于可以将评论保存到数据库中了。谢谢:-)
猜你喜欢
  • 2015-02-23
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 2015-04-10
  • 1970-01-01
相关资源
最近更新 更多