【问题标题】:ActiveAdmin - Edit Devise user without changing passwordActiveAdmin - 编辑设计用户而不更改密码
【发布时间】:2013-05-12 16:22:14
【问题描述】:

我尝试这样做。不幸的是,我在覆盖更新方面遇到了问题,我不知道如何正确地做到这一点。我在另一个地方这样做的方式是:

if params[:user][:password].blank?
  params[:user].delete("password")
  params[:user].delete("password_confirmation")
end
# ...
user.save!

所以我试图覆盖update

def update
  if params[:user][:password].blank?
    params[:user].delete("password")
    params[:user].delete("password_confirmation")
  end
  super
end

但它不起作用。我仍然在密码输入附近得到can't be blank。如何实现预期行为?

【问题讨论】:

    标签: ruby-on-rails ruby devise passwords activeadmin


    【解决方案1】:

    我接受@anonymousxxx 的回答并添加以下内容:

    如果您使用的是 rails admin,您可以按如下方式覆盖控制器“用户”:

    #app/admin/user.rb
    controller do
      def update
        if params[:user][:password].blank? && params[:user][:password_confirmation].blank?
          params[:user].delete("password")
          params[:user].delete("password_confirmation")
        end
        super
      end
    end
    

    您还应该注意,如果您有用户模型验证,请指定何时应用此类验证,例如:

    validates :name, :email, presence: true
    validates :password, :password_confirmation, presence: true, on: :create
    validates :password, confirmation: true
    

    这允许我仅在创建新用户并在不更改密码的情况下进行更新时验证密码是否存在。

    我希望这会有所帮助。

    【讨论】:

    • 除了将validates添加到模型中以使该字段不需要之外,您还可以在app/admin/users.rb中的form do |f|块中使用以下内容:f.input :password, required: f.object.new_record?
    【解决方案2】:

    将此代码添加到您的用户模型中。这将为您解决问题。

    # User.rb
    
    private    
    def password_required?
      new_record? ? super : false
    end  
    

    【讨论】:

    • 应该被标记为答案
    • 请注意,这对密码确认字段有副作用。例如,当用户想要更改他的密码时,不再需要 password_confirmation 字段..
    【解决方案3】:

    这对我有用:

    def update
         @user = User.find(current_user.id)
         params[:user].delete(:current_password)
         if @user.update_without_password(params[:user])
           redirect_to ....
         else
           render ....
         end
    end
    

    def update
        if params[:user][:password].blank? && params[:user][:password_confirmation].blank?
            params[:user].delete(:password)
            params[:user].delete(:password_confirmation)
        end
        super
    end
    

    source

    【讨论】:

    • 我的解决方案在删除 validates :password, :presence => true 后也有效。我认为,Device 的验证就足够了。
    猜你喜欢
    • 1970-01-01
    • 2014-10-23
    • 2015-08-05
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多