嵌套属性和params.require错误

时间:2014-10-26 21:09:59

标签: ruby-on-rails-4 nested-form-for

我是新手上的ruby on rails espacially nestes forms。我试图以相同的形式创建一个作者和一本书,知道它们之间存在多对多关系,我的代码如下所示。 book.rb

class Book < ActiveRecord::Base
has_many :exemplaires
has_many :talks, inverse_of: :book
has_many :subjects, through: :writings
has_many :writings
has_many :authors, through: :talks
accepts_nested_attributes_for :authors
validates :title, presence: true

end

author.rb:

class Author < ActiveRecord::Base
 has_many :talks
 has_many :books, through: :talks
end

talk.rb

class Talk < ActiveRecord::Base
 belongs_to :book
 belongs_to :author
end

book_controller.rb

class BooksController < ApplicationController

  def index

 end
 def list
   @books= Book.all
 end
 def new
   @book = Book.new
   @author=@book.authors.new
 end
 def create
    @book= Book.new(book_params)
    if @book.save
     flash[:notice]='goood'
     redirect_to admin_manage_path
    else
     flash[:alert]='ouups'
     redirect_to root_url
    end
  end



  private

  def book_params
   params.require(:book).permit(:title, :pages, :resume, :authors_attributes)
  end
  end

书籍\ new.html.erb

<h1>Add new book</h1>
  <%= form_for(@book) do |form| %>
     <%= form.label :title %>
     <%= form.text_field :title %>
     <%= form.fields_for :authors do |tag_form| %>

       <%= tag_form.label :f_name %>
       <%= tag_form.text_field :f_name %>
    <% end %>

   <%= form.submit "Submit" %>
 <% end %>

我得到的错误

  

BooksController处理#create as HTML     参数:{&#34; utf8&#34; =&gt;&#34;✓&#34;,&#34; authenticity_token&#34; =&gt;&#34; qpGng8tOiC / B5VX2tphuhAe + Wq1vx7it1vEO6XmwZmI =&#34;, &#34; book&#34; =&gt; {&#34; title&#34; =&gt;&#34; booooooooooooook&#34;,&#34; authors_attributes&#34; =&gt; {&#34; 0&# 34; =&gt; {&#34; f_name&#34; =&gt;&#34; auuuuuuuuuuuuuuuuuthor&#34;}}},&#34;提交&#34; =&gt;&#34;提交&#34;}   未允许的参数:authors_attributes

1 个答案:

答案 0 :(得分:1)

您还需要将authors_attributes字段列入白名单:

  def book_params
   params.require(:book).permit(:title, :pages, :resume, authors_attributes: [:f_name])
  end