簡體   English   中英

一個簡單的Ruby on Rails和Angularjs項目出現#500錯​​誤

[英]#500 error with a simple Ruby on Rails and Angularjs project

感謝您抽出寶貴時間為我解決此問題。 我是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

我不確定為什么會收到此錯誤。 我很感謝我能得到的任何幫助。 謝謝!

從您的控制器看來,您不允許/考慮強參數

在控制器中,您需要一個方法來指示模型允許使用哪些參數。

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

您收到一個ForbiddenAttributesError

您需要明確指定將哪些參數列入白名單以進行大規模更新: http : //edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

這是一個類似問題的解決方案: 創建新用戶時出現ActiveModel :: ForbiddenAttributesError

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM