【问题标题】:ActiveModel::ForbiddenAttributesError in BooksController#createBooksController#create 中的 ActiveModel::ForbiddenAttributesError
【发布时间】:2014-03-18 09:53:20
【问题描述】:

当我使用 /books/new 访问我的 new.erb 文件时,我的应用程序名称是 LibraryWebApplication,它提供了表格,然后我在表格中填写了标题、价格、描述,然后我点击了按钮创建它将跟随 url /books/create 但它没有将数据存储到数据库中,它显示以下错误 BooksController#create 中的 ctiveModel::ForbiddenAttributesError ActiveModel::ForbiddenAttributesError 我是 Rails 新手,无法找到解决方案 提取的源代码(第 13 行附近):

      def create
          @book = Book.new(params[:book])-----this is line no:13
          if @book.save
                redirect_to :action => 'list'
          else

Rails.root: D:/RailsAppsExamples/LibrarayWebApplication

堆栈跟踪是

    Started POST "/books/create" for 127.0.0.1 at 2014-03-18 14:58:25 +0530
    Processing by BooksController#create as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"TfBODzvGFAE6RkCmfPAAx/EhkSJkCeYUemr129dKYjc=", "book"=>{"title"=>"Advanced Physics", "price"=>"523", "subject_id"=>"2", "description"=>"mathsbk"}, "commit"=>"Create"}
    Completed 500 Internal Server Error in 0ms

    ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):
      app/controllers/books_controller.rb:13:in `create'


      Rendered c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.0ms)
      Rendered c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (15.6ms)
      Rendered c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (15.6ms)
      Rendered c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (62.5ms)
    [2014-03-18 15:03:14] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true


    Started POST "/books/create" for 127.0.0.1 at 2014-03-18 15:04:48 +0530
    Processing by BooksController#create as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"TfBODzvGFAE6RkCmfPAAx/EhkSJkCeYUemr129dKYjc=", "book"=>{"title"=>"Advanced Physics", "price"=>"523", "subject_id"=>"2", "description"=>"mathsbk"}, "commit"=>"Create"}
    Completed 500 Internal Server Error in 0ms

    ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):
      app/controllers/books_controller.rb:13:in `create'


      Rendered c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.0ms)
      Rendered c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (31.2ms)
      Rendered c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.0ms)
      Rendered c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (78.1ms)

我有两个模型

book.rb

    class Book < ActiveRecord::Base
        belongs_to :subject
        validates_presence_of :title
      validates_numericality_of :price, :message=>"Error Message"
    end

主题.rb

    class Subject < ActiveRecord::Base
        has_many :books
    end
    my controller is
    books_controller.rb
    class BookController < ApplicationController
       def list
          @books = Book.find(:all)
       end
       def show
          @book = Book.find(params[:id])
       end
       def new
          @book = Book.new
          @subjects = Subject.find(:all)
       end
       def create
          @book = Book.new(params[:book])
          if @book.save
                redirect_to :action => 'list'
          else
                @subjects = Subject.find(:all)
                render :action => 'new'
          end
       end

我的 routes.rb 是

    LibrarayWebApplication::Application.routes.draw do
        get 'books/new'
        post 'books/create'
      get 'books/list'
       get 'books/show'
      get 'books/edit'
     get 'books/show_subjects'
    end

new.erb 文件是

    <h1>Add new book</h1>
    <%= form_tag :action => 'create' %>
    <p><label for="book_title">Title</label>:
    <%= text_field 'book', 'title' %></p>
    <p><label for="book_price">Price</label>:
    <%= text_field 'book', 'price' %></p>
    <p><label for="book_subject">Subject</label>:
    <%= collection_select(:book,:subject_id,@subjects,:id,:name) %></p>
    <p><label for="book_description">Description</label><br/>
    <%= text_area 'book', 'description' %></p>
    <%= submit_tag "Create" %>
    <%= link_to 'Back', {:action => 'list'} %>

迁移文件是

20140318084539_books.rb

    class Books < ActiveRecord::Migration
     def self.up
         create_table :books do |t|
      t.column :title, :string, :limit => 32, :null => false
      t.column :price, :float
      t.column :subject_id, :integer
      t.column :description, :text
      t.column :created_at, :timestamp
         end
      end

      def self.down
        drop_table :books
      end
    end

20140318084609_subjects.rb

    class Subjects < ActiveRecord::Migration
      def self.up
          create_table :subjects do |t|
           t.column :name, :string
        end
        Subject.create :name => "Physics"
        Subject.create :name => "Mathematics"
        Subject.create :name => "Chemistry"
        Subject.create :name => "Psychology"
        Subject.create :name => "Geography"
      end

      def self.down
          drop_table :subjects
      end
    end

上面的代码是在数据库中建表的,是不是必须在database.yml中写测试和生产...可以只写开发吗...

我正在使用带有 Eclipse 插件的 Rails4.0.3

【问题讨论】:

  • 这个问题经常出现在 SO 上。查看右侧的链接,它们会为您指明正确的方向(提示:强参数)。
  • 批量分配是什么意思
  • 在强参数中是方法应该与控制器的方法名称有关吗?
  • 来自docs:由于参数强,Action Controller 参数在被列入白名单之前禁止用于 Active Model 批量分配。
  • 我无法编写强参数显示错误我是 ruby​​ 和 rails 新手

标签: ruby-on-rails-4


【解决方案1】:

我真的建议您阅读 railsguides,因为您的代码存在一些严重的问题。当我坚持你的问题时,答案是你必须使用强参数。那是什么意思?好吧,强参数决定了哪些属性可以列入白名单。

在通过 attr_accessible 在模型中列入白名单的 Rails 4 属性之前。 Rails 4 使用强参数,属于控制器。

我将举一个基本的例子:

  def create
    @book = Book.new(book_params)

    <rest of code>
  end

private
  def book_params
    params.require(:book).permit(:title, :content)
  end

现在属性 title 和 content 不再被禁止,因为您使用强参数明确允许它们。

我想我应该写一篇专门针对强参数的文章,因为它们似乎有些混乱。在这里你可以看到一个带有强参数的示例控制器:http://rails4guides.com/articles/clean-code-rails-style-guide

【讨论】:

  • 好的,我会接受的。 params.require(:book).permit(:title, :content) 这个title和content是form的参数吗?
  • 是的,这只是一个例子。在这种情况下,只能访问书籍的标题和内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多