我正在尝试在我的Rails4应用程序中处理嵌套表单,但我遇到了has_one关系问题,因为所有GEM文档仅适用于has_many。当我尝试创建新的考试时,应用程序会抛出“未经许可的参数:exam_statuses”消息。可能我对单数和复数名称做错了,但是请你检查这段代码有什么问题。这是我的代码;
examination.rb:
class Examination < ActiveRecord::Base
has_one :exam_status, dependent: :destroy
accepts_nested_attributes_for :exam_status, :reject_if => :all_blank, :allow_destroy => true
end
examination_controller.rb:
.....
def new
@examination = Examination.new
end
def create
@examination = Examination.new(examination_params)
respond_to do |format|
if @examination.save
format.html { redirect_to examinations_path, notice: 'success' }
else
format.html { render action: 'new' }
end
end
end
private
def set_examination
@examination = Examination.find(params[:id])
end
def examination_params
params.require(:examination).permit(:name, :shortname, :fee, :exam_status => [:first_application_date, :last_application_date, :examination_id])
end
views / examinations / new.html.erb =&gt;
<%= simple_form_for(@examination) do |f| %>
<%= f.input :name %>
<%= f.input :shortname %>
<%= f.input :fee %>
<%= f.simple_fields_for :exam_status do |exam_status| %>
<%= render 'exam_status_fields', :f => exam_status %>
<% end %>
<% end %>
观点/考试/ _exam_status_fields.html.erb =&gt;
<div class="nested-fields">
<%= f.input :first_application_date, as: :datetime %>
<%= f.input :last_application_date, as: :datetime %>
<%= f.input :examination_id %>
</div>
日志文件=&gt;
Started POST "/examinations" for 127.0.0.1 at 2014-07-03 16:43:30 +0300
Processing by ExaminationsController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"uYpiZ9Z1txaJ1mib+NEAG7Ckwm9F3TyNQ6jRpYz3ncA=",
"examination"=>{"name"=>"nnnnn", "shortname"=>"nnnnnn", "fee"=>"33",
"exam_statuses"=>{"first_application_date(3i)"=>"3", "first_application_date(2i)"=>"7", "first_application_date(1i)"=>"2014", "first_application_date(4i)"=>"16", "first_application_date(5i)"=>"43", "last_application_date(3i)"=>"5", "last_application_date(2i)"=>"7", "last_application_date(1i)"=>"2014", "last_application_date(4i)"=>"16", "last_application_date(5i)"=>"43", "examination_id"=>""}}}
Unpermitted parameters: exam_statuses
答案 0 :(得分:2)
这里有一些问题。
<强> 1。控制器强>
在new
方法中,您需要为exam_status
构建examination
:
# GET /examinations/new
def new
@examination = Examination.new
@examination.build_exam_status
end
在您的examination_params
方法中,您需要将其更改为:
def examination_params
params.require(:examination).permit(:name, :shortname, :fee, exam_status_attributes: [:first_application_date, :last_application_date, :_destroy])
end
请注意:exam_status
需要exam_status_attributes
,并且它不需要examination_id
param(Rails负责处理)。另请注意,我添加了_destroy
。这是用于销毁对象的标志。
<强> 2。嵌套字段部分
从部分中删除examination_id
字段。
<div class="nested-fields">
<%= f.input :first_application_date, as: :datetime %>
<%= f.input :last_application_date, as: :datetime %>
</div>
这些更改将解决问题。