【问题标题】:ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError)ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError)
【发布时间】:2017-08-10 16:11:42
【问题描述】:

我在这方面遇到了很多问题,但我无法从他们那里找到解决方案。 customers_controller.rb 是这样的:

def create
@customers = Customer.new(params)
respond_to do |format|
  if @customers.save
    format.json { render json: @customers.to_json }
  else
    format.json { render json: @customers.errors,
      status: :unprocessable_entity }
  end
end
end

class Customer < ActiveRecord::Base
end

models/customer.rb是这样的:

class Customer < ActiveRecord::Base
end

params = ActionController::Parameters.new({
  customer: {
    first_name: "Godson",
    last_name:  "Chukwu",
    username:   "Son",
    email:      "godson@son.org"
 }
})
permitted = params.require(:customer).permit(:first_name, :last_name,                  :username, :email)
permitted
permitted.permitted?
Customer.first.update!(permitted)

packs/customers.js angular 4 代码的前端是这样的:

import "hello_angular/polyfills";
import { Component, NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { Http,Response, HttpModule, Headers, RequestOptions } from     "@angular/http";
import                        "rxjs/add/operator/map";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";

   var CustomerFormComponent = Component({
     selector: "shine-customer-form",
     template: '<header class="panel-heading">
       <h1 class="h3">
         Customer 
       </h1>
     </header>
     <section class="panel-body">
       <div class="container">
         <form novalidate #customerRef="ngForm"  (ngSubmit)="submit(customerRef.value)">
          <div class="row">
            <div class="col-md-3 form-group">
              <label class="sr-only" for="first-name">
                First Name 
              </label> 
              <input type="text" class="form-control" name="first_name" 
                     placeholder="First name" ngModel #first_nameRef="ngModel"> 
            </div>
            <div class="col-md-3 form-group">
              <label class="sr-only" for="last-name">Last Name</label>
              <input type="text" class="form-control" name="last_name"
                        placeholder="Last name" ngModel #last_nameRef="ngModel">
            </div>
            <div class="col-md-3 form-group">
              <label class="sr-only" for="username">Username</label>
              <input type="text" class="form-control" name="username" 
                        placeholder="Username" ngModel #usernameRef="ngModel">
            </div>
            <div class="col-md-3 form-group">
              <label class="sr-only" for="email">Email</label>
              <input type="text" class="form-control" name="email" 
                      placeholder="Email" ngModel #emailRef="ngModel">
            </div>
          </div>
          <button type="submit" class="btn btn-primary">Submit</button>
        </form>
        <pre>{{customerRef.value | json }}<`enter code here`/pre>
      </div>
    </section>
    '
    }).Class({
    constructor: [
      Http,
      function(http) {
        this.keywords = null;
        this.customer = null;
        this.http      = http;
      }
    ],
    submit: function(customer, value){
    var headers = new Headers('authentication', `wsWPhTlJAmt1IcyNq1FCyivsAVhHq1iDCKRXOgOQock`);
      var headers = new Headers({ 'Content-Type': 'application/json'} );
      var options = new RequestOptions({ headers: headers});
      var body = JSON.stringify(customer);

      //var options = new RequestOptions({headers: headers});

      var create = {};
      //var body = JSON.stringify(customer);
      //create[customer] = value;
      this.http.post(
        "/customers", body, options
      )
      .map(function(Response){
        this.Response.json();
      })
      .subscribe(
        function(response) {
          this.response.json();
          console.log('receive response');
        },

        function(response) {
          window.alert(response);
        }
      );
    }
});

var CustomerAppModule = NgModule({
imports:      [ BrowserModule,
                FormsModule,
                HttpModule
             ],
declarations: [ CustomerFormComponent ],
bootstrap:    [ CustomerFormComponent ]
})
.Class({
constructor: function() {}
});

platformBrowserDynamic().bootstrapModule(CustomerAppModule);

下面是我控制台的输出:

16:18:20 rails.1   | app/controllers/customers_controller.rb:27:in `create'
16:30:55 rails.1   | Started GET "/customers" for 127.0.0.1 at 2017-08-10 16:30:55 +0100
16:30:56 rails.1   | Processing by CustomersController#index as HTML
16:30:57 rails.1   |   Customer Load (28.9ms)  SELECT  "customers".* FROM "customers" ORDER BY "customers"."id" ASC LIMIT $1  [["LIMIT", 1]]
16:30:57 rails.1   |    (0.3ms)  BEGIN
16:30:57 rails.1   |    (0.4ms)  COMMIT
16:30:57 rails.1   |   Rendering customers/index.html.erb within layouts/application
16:30:57 rails.1   |   Rendered customers/index.html.erb within layouts/application (72.5ms)
16:30:57 rails.1   | Completed 200 OK in 786ms (Views: 329.2ms | ActiveRecord: 99.1ms)
16:30:57 rails.1   | 
16:30:57 rails.1   | 
16:32:56 rails.1   | Started POST "/customers" for 127.0.0.1 at 2017-08-10 16:32:56 +0100
16:32:56 rails.1   | Processing by CustomersController#create as HTML
16:32:56 rails.1   |   Parameters: {"first_name"=>"Dan", "last_name"=>"Nwa", "username"=>"Sola", "email"=>"kman1@kman.net", "customer"=>{"first_name"=>"Dan", "last_name"=>"Nwa", "email"=>"kman1@kman.net", "username"=>"Sola"}}
16:32:56 rails.1   | Can't verify CSRF token authenticity.
16:32:56 rails.1   | Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)
16:32:56 rails.1   | 
16:32:56 rails.1   | 
16:32:56 rails.1   |   
16:32:56 rails.1   | ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):
16:32:56 rails.1   |   
16:32:56 rails.1   | app/controllers/customers_controller.rb:27:in `create'

firefox浏览器中的网络预览请求参数是这样的:

Request

Parameters:

{"first_name"=>"Dan", "last_name"=>"Nwa", "username"=>"Sola", "email"=>"kman1@kman.net", "customer"=>{"first_name"=>"Dan", "last_name"=>"Nwa", "email"=>"kman1@kman.net", "username"=>"Sola"}}

我哪里弄错了?

【问题讨论】:

  • 您应该包含一个名为“authenticity_token”的隐藏字段和由(Rails 助手)form_authenticity_token987654326@设置的值

标签: ruby-on-rails angular4-forms


【解决方案1】:

因为您是从“Angular”提交的,所以您没有传递跨站请求伪造 (CSRF) 令牌。

您可以通过多种方式解决此问题,但有两种选择。

在你的 application_controller.rb 添加

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session
end

或者在你的 customer_controller.rb 中添加

skip_before_action :verify_authenticity_token

如果您只需要跳过跨站请求伪造 (CSRF) 进行创建,您可以这样做。

skip_before_action :verify_authenticity_token, only: :create

【讨论】:

  • 谢谢@MrYoshiji,我已经添加了protect_from_forgery with: :null_session,application_controller.rb。现在,当我在 customers_controller.rb 中将私有 customer_params 方法作为参数添加到 create 方法时,出现以下错误:ActionController::UnknownFormat (ActionController::UnknownFormat): 。同时,表单现在正在向数据库提交数据。但似乎问题来自 customers_controller.rb 创建方法中的respond_to do |format|。我将如何解决这个问题?谢谢。
  • 这是我的控制台日志:19:45:55 rails.1 | Parameters: {"first_name"=&gt;"Newman", "last_name"=&gt;"Kalu", "username"=&gt;"Didi", "email"=&gt;"new@newer.ng", "customer"=&gt;{"first_name"=&gt;"Newman", "last_name"=&gt;"Kalu", "email"=&gt;"new@newer.ng", "username"=&gt;"Didi"}} 19:45:55 rails.1 | Unpermitted parameter: :customer 19:45:55 rails.1 | SQL (13.2ms) INSERT INTO "customers" (17.1ms) COMMIT 19:45:55 rails.1 | Completed 406 Not Acceptable in 35ms (ActiveRecord: 30.6ms) 19:45:55 rails.1 | ActionController::UnknownFormat (ActionController::UnknownFormat): 跳过了一些输出。
  • 我应该第一次看到这个但你传递了{"first_name"=&gt;"Newman", "last_name"=&gt;"Kalu", "username"=&gt;"Didi", "email"=&gt;"new@newer.ng", "customer"=&gt;{"first_name"=&gt;"Newman", "last_name"=&gt;"Kalu", "email"=&gt;"new@newer.ng", "username"=&gt;"Didi"}。在发布之前,您需要将这些参数包装在 customer 中的 packs/customers.js 中。 var body = JSON.stringify(customer); 应该是 var body = JSON.stringify({ customer: customer });
  • @nzajt,当我将其修改为var body = JSON.stringigy({ customer: customer }) 时,我在控制台中得到了这个输出:Parameters: {"customer"=&gt;{"first_name"=&gt;"Wisdom", "last_name"=&gt;"Biggs", "username"=&gt;"Wiz", "email"=&gt;"wiz@wiz.com"}} Unpermitted parameter: :customer 02:11:37 rails.1 | SQL (1.0ms) INSERT INTO "customers" ... (0.2ms) ROLLBACK Completed 500 Internal Server Error in 4ms (ActiveRecord: 1.5ms) ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR: null value in column "first_name" violates not-null constraint 跳过了一些输出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多