【问题标题】:#500 error with a simple Ruby on Rails and Angularjs project#500 一个简单的 Ruby on Rails 和 Angularjs 项目的错误
【发布时间】:2016-02-10 18:25:23
【问题描述】:

感谢您花时间帮助我解决这个问题。我是 Ruby 新手,所以这似乎是一个简单的答案。我创建了一个 api 来允许 Ruby 和 Angularjs 相互交流。 API 如下:

class EntriesController < ApplicationController
respond_to :json
protect_from_forgery

def index
    respond_with Entry.all
end

def show
    respond_with Entry.find(params[:id])
end

def create
    respond_with Entry.create(params[:entry])
end

def update
    respond_with Entry.update(params[:id], params[entry])
end

def destroy
    respond_with Entry.destroy(params[:id])
end
end

我的 Angular js 控制器是:

@app = angular.module("angRails",["ngResource", "ngMaterial", "ngAnimate", "ngAria"]);

@mainCTRL = ["$scope", "$resource", ($scope, $resource) ->

  Entry = $resource("/entries/:id", {id: "@id"}, {update: {method: "PUT"}})

  $scope.newName = "";

  $scope.entries = Entry.query();


  $scope.addEntry = ->

unless $scope.newName is ""
  entry = Entry.save($scope.newName)
  console.log(JSON.stringify(entry));
  $scope.entries.push(entry);
  console.log("add Entry function");
  $scope.newName = "";

]


app.controller("mainCTRL", mainCTRL);

$scope.entries = Entry.query(); 工作正常,但创建条目根本不起作用。我得到错误:

POST http://localhost:3000/entries 500 (Internal Server Error)

ActiveModel::ForbiddenAttributesError in EntriesController#create
ActiveModel::ForbiddenAttributesError

Extracted source (around line #14):
12
13 def create
14 respond_with Entry.create(params[:entry])
15 end

我不确定为什么会收到此错误。我很感激我能得到的任何帮助。谢谢!

【问题讨论】:

    标签: javascript ruby-on-rails ruby angularjs general-network-error


    【解决方案1】:

    您的控制器会显示您不允许/考虑strong params

    在您的控制器中,您需要一个方法来指示您的模型允许哪些参数。

    def create
      @entry = Entry.new(entry_params)
      @entry.save
      respond_with(@entry)
    end 
    
    private 
    def entry_params
      params.require(:entry).permit(:attribute, :another_attribute)
    end
    

    【讨论】:

      【解决方案2】:

      您将收到ForbiddenAttributesError

      您需要明确指定哪些参数被列入白名单以进行大规模更新: http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

      这是一个类似问题的解决方案: ActiveModel::ForbiddenAttributesError when creating new user

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-13
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        • 2012-05-09
        相关资源
        最近更新 更多