【问题标题】:Allowing a nested attribute for a User with Devise in Rails 4在 Rails 4 中允许用户使用 Devise 的嵌套属性
【发布时间】:2014-03-14 08:37:13
【问题描述】:

我正在从 Rails 3.2 升级到 4.0,并且正在为我的 User 模型使用 Devise。以前我的User 模型中有attr_accessible 属性:

attr_accessible :username, :first_name, :last_name, :email, :password, :password_confirmation, :remember_me

现在根据Devise documentation for strong parameters,我必须在application_controller.rbbefore_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] 作为参数。当我简单地保存用户编辑表单而不进行任何更改时,发生了 3 个主要问题:

  1. 显示错误:“员工通知电子邮件已被接收”(我在Staff 模型中有validates :notification_email, uniqueness: true, allow_nil: true
  2. 显示错误:“员工项目不能为空”(我在Staff 模型中有validates_presence_of :project_id
  3. 即使我收到了这 2 个错误,与 user 关联的 staff 模型也被清除了,所有属性都设置为 nil,除了 notification_email。这包括user_id 字段,因此staff 对象不再连接到user

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 devise strong-parameters


    【解决方案1】:

    这些是嵌套属性,所以你需要通过以下方式添加它们:

    devise_parameter_sanitizer.for(:sign_up) { |u|
      u.permit(:username, :staff_attributes => [:name, :position, :etc]) 
    }
    

    【讨论】:

    • 哇,这太令人惊讶了。我在permit 电话中添加了这个:, staff_attributes: [:notification_email]。因为我只希望用户能够更新他们的notification_email,如果他们是员工的话。最终发生的是所有其他字段,包括Staffuser_id 字段被设置为nil!这样用户就不再是工作人员了!有没有办法只能更新 1 个员工属性?或者至少不将所有其他字段设置为nil?此外,当我编辑用户时,我收到一个错误,即需要 staff 的另一个字段,即使它仍然是 niled 所有字段。
    • 问题是我没有:id 作为staff_attributes 指向的数组中的元素之一。现在一切都很完美!
    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多