简体   繁体   English

使用设计多态关联更新用户

[英]Update user with devise polymorphic association

I experiencing an issue on the update of a polymorphic association. 我在更新多态关联时遇到问题。 Actually, I've several type of users such as Admin , Customer , etc... But on the update of a customer (for example), it fails because devise ask for a password. 实际上,我有几种类型的用户,例如AdminCustomer等。但是在更新客户(例如)时,由于设计要求输入密码而失败。

I've the User model which only have devise logic: 我有User模型,只有设计逻辑:

class User < ActiveRecord::Base
  devise  :database_authenticatable,
          :registerable,
          :recoverable,
          :rememberable,
          :trackable,
          :validatable

  belongs_to :role, polymorphic: true
end

customer.rb: customer.rb:

class Customer < ActiveRecord::Base
  has_one :user, as: :role, dependent: :destroy
end

And on the controller side, customers_controller.rb: 在控制器方面, customers_controller.rb:

def update
  if @customer.update customer_params
    redirect_to dashboard_path, flash: { success: t('validation.update', model: @customer.class.model_name.human.downcase) }
  else
    render 'edit'
  end
end

private

def customer_params
  params.require(:customer).permit(:firstname, :lastname, user_attributes: [:email, :password, :password_confirmation])
end

Here is my form view: 这是我的表单视图:

= simple_form_for @customer do |f|
  .form-inputs
    = f.fields_for :user do |u|
      = u.input :email, required: true, autofocus: true
      = u.input :password, autocomplete: 'off', hint: t('devise.registrations.edit.leave_blank_if_you_don_t_want_to_change_it'), required: false
      = u.input :password_confirmation, required: false
      = u.input :current_password, hint: t('devise.registrations.edit.we_need_your_current_password_to_confirm_your_changes'), required: true

    = f.input :firstname
    = f.input :lastname

I see that in the form you have added required: false for password and password_confirmation field. 我看到在您添加的表格中, required: false passwordpassword_confirmation字段为required: false

The required attribute is a boolean attribute. 必需属性是布尔属性。 When present, it specifies that an input field must be filled out before submitting the form. 如果存在,它指定提交表单之前必须填写输入字段。

BUT that is not going to restrict Devise from asking for password. 但是不会限制Devise要求输入密码。 By default, in Devise its mandatory which will performed every time you update a record. 默认情况下,在Devise中,其强制性命令将在每次更新记录时执行。

If you want to update the record without providing password then follow the guidelines mentioned in Devise How To: Allow users to edit their account without providing a password 如果要在不提供密码的情况下更新记录,请遵循“设计方法:允许用户在不提供密码的情况下编辑其帐户”中提到的准则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM