【发布时间】:2014-07-18 13:05:23
【问题描述】:
我有两个模型 Employee 和 Documents 如下:
Employee.rb
class Employee < ActiveRecord::Base
has_one :document #,dependent: :destroy
attr_accessible :age, :dob, :empNo, :first_name, :gender, :last_name, :middle_name, :document_attributes
accepts_nested_attributes_for :document
validates :first_name, presence: true , length: { maximum: 50 }
validates :empNo, presence: true, uniqueness:{ case_sensitive: false }
validates_length_of :empNo, :minimum => 5, :maximum => 5
#before save { |user| user.email = email.downcase }
end
文档.rb
class Document < ActiveRecord::Base
belongs_to :employee,foreign_key: "empno"
attr_accessible :idate, :iedate, :insuranceno, :iqamano, :iqedate, :iqidate, :passportno, :pedate, :pidate, :vedate, :vidate, :visano
end
控制器文件是employees_controller.rb(我只展示了new,create,show funcs)
def show
@employee = Employee.find(params[:id])
@document=Document.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @employee }
end
end
# GET /employees/new
# GET /employees/new.json
def new
@employee = Employee.new
@document= Document.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json=>{:employee=> @employee,:document=>@document}, status: :created, :location=>{:employee=> @employee,:document=>@document} }
end
end
# POST /employees
# POST /employees.json
def create
@employee = Employee.create!(params[:employee])
@document = Document.create!(params[:document])
respond_to do |format|
if @employee.save and @document.save
format.html { redirect_to @employee, notice: 'Employee was successfully created.' }
format.json { render :json=>{:employee=> @employee,:document=>@document}, status: :created, location: @employee }
else
format.html { render action: "new" }
format.json { render json: @employee.errors, status: :unprocessable_entity }
end
end
end
当我创建一个新员工时,我收到以下错误
ActiveModel::MassAssignmentSecurity::Error in EmployeesController#create
Can't mass-assign protected attributes: document
requsts 参数很好,如下所示
{"utf8"=>"✓",
"authenticity_token"=>"vXSnbdi+wlAhR5p8xXvTWhi85+AVZgOZufClx73gc8Q=",
"employee"=>{"empNo"=>"11111",
"first_name"=>"Thaha",
"middle_name"=>"Muhammed",
"last_name"=>"Hashim",
"age"=>"25",
"gender"=>"M",
"dob(1i)"=>"2014",
"dob(2i)"=>"7",
"dob(3i)"=>"18",
"document"=>{"passportno"=>"bycucde63"}},
"commit"=>"Create Employee"}
我已经浏览了几乎所有关于 stackoverflow 的帖子来处理这个问题,而且大部分问题都与
- 不使用
attr_accessible - 不使用
accepts_nested_attributes_for - 不使用
:document_attributes
如果我将config.active_record.whitelist_attributes 的值更改为 false,那么错误就会消失(开发人员日志中存在相同的警告)并且 两个模型都已创建,但只有员工模型的属性是当文档模型的属性为 nil 时,填充传递的值。
编辑 #1 如果我尝试将 :document 添加到 attr_accessible ,则会收到以下错误
ActiveRecord::AssociationTypeMismatch in EmployeesController#create
我在这里做错了什么?
【问题讨论】:
标签: ruby-on-rails-3 nested-attributes mass-assignment