我正在创建接受嵌套属性的表单: #doctor.rb
#user.rb
has_one :doctor
accepts_nested_attributes_for :doctor, reject_if: proc { |attributes| attributes['cartridge_name'].blank? }, allow_destroy: true
我的强大参数:
def user_params
params.require(:user).permit(:name,:birthday, :address, :phone,:email, :role, :social => [],
:doctor => [:position,:department_id,:salary_type,:date_came,:monthly_salary,:percentage_salary,:id],
end
但是我收到了错误:
Doctor(#70193541488440) expected, got ActionController::Parameters(#70193536484960)
可能是关联或我强大的障碍问题。
编辑:
<%= form_for(@user, url:create_doctor_users_path) do |f| %>
<%= f.fields_for @doctor do |u| %>
<%= render 'doctor_attributes', f:u %>
<% end %>
<% end %>
EDIT2:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"birXhqxdplQMfZF5G8jDM9wi1nsBwkJfWsHcE8ZbPCxxemgR8ObmCFzODqoHAcTDo9jNMN0G0HK69A4hGy0Ddg==",
"user"=>{"name"=>"", "birthday"=>"", "address"=>"", "phone"=>"", "email"=>"",
"doctor"=>{"position"=>"", "department_id"=>"", "salary_type"=>"Зарплата", "date_came"=>"", "monthly_salary"=>"", "percentage_salary"=>""},
"educations_attributes"=>{"0"=>{"from"=>"", "to"=>"", "institution"=>"", "major"=>"", "_destroy"=>"false"}},
"job_experiences_attributes"=>{"0"=>{"from"=>"", "to"=>"", "institution"=>"", "position"=>"", "_destroy"=>"false"}}}, "commit"=>"Зарегестрировать"}
而且我认为这很重要,我正在以这种方式在控制器中进行创作:
@user = User.new
@doctor = Doctor.new
@user.job_experiences.build
@user.educations.build
我想我应该这样做:
@user.doctor.build
与job_experiences一样,但我收到错误:
undefined method `build' for nil:NilClass
答案 0 :(得分:2)
将user_params
修复为:
def user_params
params.require(:user).permit(:name,:birthday, :address, :phone,:email, :role, :social => [],
:doctor_attributes => [:position,:department_id,:salary_type,:date_came,:monthly_salary,:percentage_salary,:id]
^^^^^^^^^^^^^^^^^
end
说明:
如果您在模型中使用accepts_nested_attributes_for
,则应将permitted
参数传递为doctor_attributes
而不是doctor
,在引擎盖下创建一个对象Doctor
,因为它在你的错误中描述。
阅读关于accepts_nested_attributes_for
的精彩文章。
将表单修复为:
<%= f.fields_for :doctor, @user.build_doctor do |u| %>
<%= render 'doctor_attributes', f:u %>
<% end %>
在您的参数中,您应该看到:
"doctor_attributes"=>{" ....}
而不是:
"doctor"=>{" ....}