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 %>
嗨Rich,謝謝你。我想你是正確的。某些東西似乎正在影響屬性的構建。我將控制器代碼更改爲「2.times do @ hire.build_book end」,但仍然存在相同的問題。任何其他想法? –
我想知道這是否與我的協會有關。我在說'accep_nested_attributes_for:book',但是我的'f.fields'是'books',我的屬性是'books'? –
去拿點食物,然後看看 –