2015-11-05 96 views
2

我有一個窗體傳遞嵌套的屬性它爲'孩子'工作,但'書'似乎並沒有保存。嵌套的屬性和未經許可的參數

我有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 %> 

回答

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調用。

+0

嗨Rich,謝謝你。我想你是正確的。某些東西似乎正在影響屬性的構建。我將控制器代碼更改爲「2.times do @ hire.build_book end」,但仍然存在相同的問題。任何其他想法? –

+0

我想知道這是否與我的協會有關。我在說'accep_nested_attributes_for:book',但是我的'f.fields'是'books',我的屬性是'books'? –

+0

去拿點食物,然後看看 –