當我提交具有兩種模型 - 嵌套表單和成員信息的嵌套表單時,出現500內部服務器錯誤。在Rails中提交嵌套表單時發生內部服務器錯誤
錯誤:
500 Internal Server Error
If you are the administrator of this website, then please read this web application's log file and/or the web server's log file to find out what went wrong.
我檢查日誌文件,這是我發現了什麼:
TypeError (expected Hash (got Array) for param `child_info_attrib'):
下面是其他部分的我的Rails項目
查看(new.html.erb>
<%= form_for(@member) do |f| %>
<div class="field">
<%= f.label :gender, "Gender" %><br />
<%= f.select :gender, options_for_select(["Male", "Female"]) %>
</div>
<div class="field">
<%= f.label :fname, "First Name" %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :age, "Age" %><br />
<%= f.text_field :age %>
</div>
<div class="field">
<%= f.label :membership_id, "Membership ID" %>
<%= f.text_field :membership_id %>
</div>
<div class="field">
<%= f.label "Branch" %>
<%= f.collection_select(:branch_id, Branch.all, :id, :name) %>
</div>
<% for children_information in @member.children_informations %>
<%= fields_for "member[child_info_attrib][]", children_information do |children_info_form| %>
<div class="field">
<%= children_info_form.label :name, "Name" %><br />
<%= children_info_form.text_field :name %>
</div>
<div class="field">
<%= children_info_form.label :gender, "Gender" %><br />
<%= children_info_form.select :gender, options_for_select(["Male", "Female"]) %>
</div>
<div class="field">
<%= children_info_form.label :birthdate, "Birthdate" %><br />
nn <%= children_info_form.datetime_select :birthdate, :discard_hour => true,
:order => [:month, :day, :year], :start_year => 1900 %>
</div>
</div>
<% end %>
<% end %>`
模型(會員)
class Member < ActiveRecord::Base
has_many :children_informations
def child_info_attrib=(attribs)
attribs.each do |attrib|
children_informations.build(attrib)
end
end
end
模型(ChildrenInformation)
class ChildrenInformation < ActiveRecord::Base
belongs_to :member
end
控制器(MembersController)
class MembersController < ApplicationController
def new
@member = Member.new
@member.children_informations.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @member }
end
end
def create
@member = Member.new(params[:member])
respond_to do |format|
if @member.save
format.html { redirect_to(@member, :notice => 'Member was successfully created.') }
format.xml { render :xml => @member, :status => :created, :location => @member }
else
format.html { render :action => "new" }
format.xml { render :xml => @member.errors, :status => :unprocessable_entity }
end
end
end
開發日誌:http://pastebin.com/n9E2nyFv(會員表有很多字段)
我到目前爲止所嘗試的是省略嵌套窗體,它確實有效。
此外,我基於這種通過RailsCasts使用嵌套表單的方式(http://railscasts.com/episodes/73-complex-forms-part-1)。
如何使用嵌套表單成功提交?
預先感謝您! :)
嗨@豐啄。我試了你的答案,它確實成功提交了表單。但是當我檢查數據庫時,這些字段都是NULL,但有記錄條目。 – alucillo36
這意味着我們在進入模型時沒有正確處理它們 - 您是否有可用的參數日誌? –
如何檢索參數? – alucillo36