0

感谢您花时间帮助我解决这个问题。我是 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

我的角度 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

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

4

2 回答 2

0

从您的控制器看来,您不允许/考虑强参数

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

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
于 2016-02-10T18:33:38.647 回答
0

你得到一个ForbiddenAttributesError

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

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

于 2016-02-10T18:33:54.650 回答