使用devise多态关联更新用户

时间:2014-04-02 14:37:11

标签: ruby-on-rails devise simple-form polymorphic-associations

我遇到了更新多态关联的问题。 实际上,我有几种类型的用户,例如AdminCustomer等... 但是在客户更新(例如)时,它失败了,因为设计要求输入密码。

我的User模型只有设计逻辑:

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

在控制器端, 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

这是我的表单视图:

= 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

1 个答案:

答案 0 :(得分:0)

我在表格中看到您为required: falsepassword字段添加了password_confirmation

  

必需属性是布尔属性。它存在的时候   指定在提交之前必须填写输入字段   形式。

但这并不会限制Devise要求输入密码。默认情况下,在Devise中,每次更新记录时都会执行强制执行。

如果您想在不提供密码的情况下更新记录,请遵循设计 How To: Allow users to edit their account without providing a password

中提到的指南