如何使用设计仅更新电子邮件?

时间:2013-09-22 04:22:08

标签: ruby-on-rails devise

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

 <%= 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中的更新操作&lt;设计:: 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

1 个答案:

答案 0 :(得分: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?方法