Question

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.

I've the User model which only have devise logic:

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

  belongs_to :role, polymorphic: true
end

customer.rb:

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

And on the controller side, 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
Was it helpful?

Solution

I see that in the form you have added required: false for password and password_confirmation field.

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. By default, in Devise its mandatory which will performed every time you update a record.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top