Ajax Devise更新表单仅在没有表单错误时才有效

时间:2014-01-22 16:26:52

标签: ruby-on-rails ruby ajax devise ruby-on-rails-4

我有一个设计表单,用户可以在其中更改密码。我做了一个自定义重定向,所以它会在提交表单后返回编辑密码页面(而不是设计默认的根页面)。以下是自定义重定向的代码:

class RegistrationsController < Devise::RegistrationsController

    protected

    def after_update_path_for(resource)
        puts 'redirect is happening' #This is so I can see it in the server logs
        flash[:notice] = "Account succesfully updated"
        edit_user_registration_path
    end
end

路线:

devise_for :users, :controllers => { :registrations => :registrations }

唯一的问题是,如果更改密码成功,这只会重定向到编辑密码页面。如果不是(假设用户输入了错误的密码确认),它仍然会重定向到根页面。当有错误时,有谁知道如何正常工作?

更新:

这与我通过ajax提交表单的事实有关。更新成功后,将触发after_update_path_for方法,并将用户重定向到edit_user_registration_path,该配置为返回javascript。问题是如果没有触发after_update_path_For方法,它会像往常一样呈现edit_user_registration_path失败,除了它将它呈现为html,我已经做到了这样,页面只能通过javascript呈现。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

Devise的默认RegistrationsController更新方法如下所示:

  def update
    self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
    prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)

    if update_resource(resource, account_update_params)
      yield resource if block_given?
      if is_flashing_format?
        flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
          :update_needs_confirmation : :updated
        set_flash_message :notice, flash_key
      end
      sign_in resource_name, resource, :bypass => true
      respond_with resource, :location => after_update_path_for(resource)
    else
      clean_up_passwords resource
      respond_with resource
    end
  end

“else”是无效重定向发生的地方。您可以在自己的RegistrationsController中复制该方法,并在调用编辑路径时覆盖“respond_with resource”调用。可能有一个更优雅的解决方案,但我对AJAX还不太好。也许你可以用覆盖Devise的respond_with方法代替它?

相关问题