【问题标题】:Name Error: Angular/Rails Alternative Controller Method Issue名称错误:Angular/Rails 替代控制器方法问题
【发布时间】:2017-03-22 01:26:50
【问题描述】:

我想在 http://localhost:3000/groups.json 之类的浏览器中访问 json 以进行投票(参见代码)。运气不太好,下面是相关代码。

错误:未定义的局部变量或方法 `group_params' for #

// inject $http so we can go to http://localhost:3000/groups.json in our browser and see an array of all the groups in our database
.factory('groups', ['$http', function($http){
    //service body
    var o = {
        groups: []
    };

    // get all the groups in the service, groups.js
    o.getAll = function() {
      return $http.get('/groups.json').success(function(data){
        angular.copy(data, o.groups);
      });
    };


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

Rails 控制器:

   before_action :set_group, only: [:show, :edit, :update, :destroy, :upvote]

  def upvote
    @groups = Group.all

    respond_to do |format|
      format.html {}
      format.json { render json: @groups }
    end
  end

其他方法:

  def index
   @groups = Group.all

   respond_to do |format|
     format.html {}
     format.json { render json: @groups }
   end
  end      

 def set_group
     @group = Group.where(params[:id])
  end

完全错误:

Started GET "/groups/upvote.json" for 127.0.0.1 at 2017-03-21 21:37:22       0700
Processing by GroupsController#show as JSON
Parameters: {"id"=>"upvote"}
  Group Load (0.4ms)  SELECT  "groups".* FROM "groups" WHERE     "groups"."id" = $1 LIMIT 1  [["id", 0]]
Completed 404 Not Found in 5ms (ActiveRecord: 2.4ms)

ActiveRecord::RecordNotFound (Couldn't find Group with 'id'=upvote):
  app/controllers/groups_controller.rb:131:in `set_group'

【问题讨论】:

  • 您将set_group 称为before_actionupvote,我猜这就是问题所在。您能否也显示该方法的代码?
  • 添加,方法设置同理。它适用于没有问题的索引操作。
  • 啊,绝对不是这样。你也可以分享异常的完整堆栈跟踪吗?
  • 加载资源失败:服务器响应状态为 404(未找到)是我在控制台上得到的。这是我怀疑没有找到json所以它一定是路由问题?我还检查了导轨 c 中的路径。没有路径,所以它必须为json添加自定义路径。我正在检索一个集合,并希望通过将其吐出的路线访问它.....hmmm
  • 太棒了,谢谢@McDoku

标签: ruby-on-rails angularjs json


【解决方案1】:

总结一下我们在 cmets 中的聊天:

根据堆栈跟踪,错误是由set_group 方法引发的ActiveRecord::RecordNotFound 异常引起的,这反过来导致端点返回 404,尽管在问题中为set_group 发布的代码 sn-p 没有完全匹配。

由于upvote 操作不需要设置@group,您只需从before_action 的操作列表中删除upvote

【讨论】:

猜你喜欢
  • 2011-08-09
  • 2012-07-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
相关资源
最近更新 更多