2

我正在尝试使用此表单仅更新电子邮件,但验证失败Current password can't be blank,需要密码确认,我不知道如何取消此要求

 <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:method => :put, :id=>"email_form"}) do |f| %>
            <%= devise_error_messages! %>
            <div><%= f.label :email %>
              <br/>
              <%= f.email_field :email, :autofocus => true %></div>
            <div><%= f.submit "Update" %></div>
        <% end %>

更新 这是我在重写控制器 RegistrationsController < Devise::RegistrationsController 中的更新操作

class RegistrationsController < Devise::RegistrationsController
  def update
    @user = User.find(current_user.id)

    successfully_updated = if needs_password?(@user, params)
      @user.update_with_password(params[:user])
    else
      # remove the virtual current_password attribute update_without_password
      # doesn't know how to ignore it
      params[:user].delete(:current_password)
      @user.update_without_password(params[:user])
    end

    if successfully_updated
      set_flash_message :notice, :updated
      # Sign in the user bypassing validation in case his password changed
      sign_in @user, :bypass => true
      redirect_to after_update_path_for(@user)
    else
      render "edit"
    end
  end

  private
  def needs_password?(user, params)
    user.email != params[:user][:email] ||
      params[:user][:password].present?
  end
end
4

1 回答 1

1

只需指向其他控制器,而不是设计自己的注册控制器,并使用您自己的更新操作逻辑。

您还可以覆盖设计注册的控制器(阅读设计文档)。

例子:

# config/routes.rb
resource :profile     # Singular resource and profile 

# profiles_controller
def show
  # render your view with the for
end

def update
  current_user.update(params[:user]) # if rails < 4 use update_attributes instead
end

# _form.html.erb
<%= form_for(current_user, url: profile_path, html: { method: 'PUT' }) do |f| %>
  ...

对于第二个选项,覆盖设计自己的注册控制器,我不太喜欢这种方法,因为在这种情况下,您实际上并不是在处理注册,而是一个已经注册的用户帐户:

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password

编辑后:

我看到你正在使用第二个选项。看一下needs_password?控制器中的方法

于 2013-09-22T04:28:16.937 回答