我正在将Rails 3.2升级到4.0版本,并在我的User
模型中使用Devise。以前,我的User
模型中有attr_accessible
属性:
attr_accessible :username, :first_name, :last_name, :email, :password, :password_confirmation, :remember_me
现在根据Devise文档中的强参数,我需要在application_controller.rb
文件中的before_filter
方法中执行以下操作:
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :first_name, :last_name, :email, :password, :password_confirmation, :remember_me) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :first_name, :last_name, :email, :password, :password_confirmation, :remember_me, :current_password) }
听起来不错,但是我的User
模型中也有一个accepts_nested_attributes_for
:
accepts_nested_attributes_for :staff, reject_if: :new_record?
我应该如何在
devise_parameter_sanitizer.for(:account_update)
中指定?对我来说这不太清晰。
更新: 我尝试了以下方法:devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :first_name, :last_name, :email, :password, :password_confirmation, :remember_me, :current_password, staff_attributes: [:notification_email]) }
特别地,我在
permit
方法的参数中添加了 staff_attributes: [:notification_email]
。当我只是保存用户编辑表单而没有做任何更改时出现了三个主要问题:
- 显示错误:“Staff notification email has already been taken”(在
Staff
模型中有validates :notification_email, uniqueness: true, allow_nil: true
) - 显示错误:“Staff project can't be blank”(在
Staff
模型中有validates_presence_of :project_id
) - 尽管我收到这两个错误,与
user
关联的staff
模型被清除了,除了notification_email
外,所有属性都设置为nil
。这包括user_id
字段,因此staff
对象不再连接到user
。
permit
调用中添加了这个:, staff_attributes: [:notification_email]
。因为我只希望用户能够在成为员工的情况下更新他们的notification_email
。结果所有其他字段,包括Staff
的user_id
字段都被设置为nil
!所以用户不再是员工了!有没有办法只更新一个员工属性?或者至少不将所有其他字段设置为nil
?此外,当我编辑用户时,我收到了一个错误,说需要staff
的另一个字段,即使它仍然将所有字段设置为nil
。 - at.:id
作为staff_attributes
指向的数组中的元素之一。现在一切都完美运行! - at.