嵌套属性和未允许的参数

时间:2015-11-05 22:33:01

标签: ruby-on-rails ruby-on-rails-4 nested-attributes

我有一个传递嵌套属性的表单,它适用于' Child'但是“书籍”#39;似乎没有储蓄。

我有3个型号。每个孩子可以有2本书:

class Child < ActiveRecord::Base
 has_many :hires
 has_many :books, through: :hires
end

class Hire < ActiveRecord::Base
 belongs_to :book
 belongs_to :child
 accepts_nested_attributes_for :book
 accepts_nested_attributes_for :child
end

class Book < ActiveRecord::Base
  has_many :hires
  has_many :children, through: :hires
  belongs_to :genres
end

控制器如下所示:

class HiresController < ApplicationController

...    

 def new
     @hire = Hire.new
     2.times { @hire.build_book }
 end

 def create
    @hire = Hire.new(hire_params)

    respond_to do |format|
      if @hire.save
        format.html { redirect_to @hire, notice: 'Hire was successfully created.' }
        format.json { render :show, status: :created, location: @hire }
      else
        format.html { render :new }
        format.json { render json: @hire.errors, status: :unprocessable_entity }
      end
    end
  end

 ...    

private
    # Use callbacks to share common setup or constraints between actions.
    def set_hire
      @hire = Hire.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
        def hire_params
  params.require(:hire).permit(:child_id, books_attributes: [ :id, :book_id, :_destroy])
end
end

正在提交的哈希如下所示:

Processing by HiresController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"+2xxx==", "hire"=>{"child_id"=>"2", "books"=>{"book_id"=>"5"}}, "commit"=>"Create Hire"}
Unpermitted parameter: books

我无法理解为什么我会收到不允许的params错误?有什么建议吗?

*编辑 - 包含视图,因为我现在怀疑这可能会起作用*

<%= form_for(@hire) do |f| %>

<%= f.select(:child_id, Child.all.collect {|a| [a.nickname, a.id]}) -%>
<%= f.label :child_id %><br>

<%= f.fields_for :books do |books_form| %>
<%= books_form.label :book_id %><br>
<%= books_form.select(:book_id, Book.all.collect {|a| [a.Title, a.id]}) -%>
<%= books_form.label :book_id %><br>
<%= books_form.select(:book_id, Book.all.collect {|a| [a.Title, a.id]}) -%>
<% end %>


<div class="actions">
<%= f.submit %>
</div>
<% end %>

1 个答案:

答案 0 :(得分:0)

您需要使用以下内容:

#app/controllers/hires_controller.rb
class HiresController < ApplicationController
   def new
      @hire = Hire.new
      2.times do
         @hire.build_book
      end
   end
end

其余部分看起来还不错。

你遇到的问题很典型;当您使用f.fields_for时,您必须构建关联对象,否则fields_for不会创建正确的字段名称。

您正在寻找的字段名称为[books_attributes][0][book_id]等。

由于您的表单传递了您期望的所有属性(没有_attributes后缀),我只能推测您关联对象的构建不正确:

2.times { @hire.books.build }

......应该......

2.times { @hire.build_book }

当你有单数关联时,你必须单独构建关联对象:build_object,而复数,你可以使用plural.build调用。