在Ajax注册Rails dev上返回错误

时间:2018-08-20 08:19:13

标签: ruby-on-rails ajax devise

我的客户通过AJAX呼叫在我的网站上注册。如果他们注册成功,它会很好地工作,但是如果他们的表单中有错误,那么它就不会成功。 (客户端什么都不做)。

仅供参考,我使用本教程添加了AJAX注册:AJAX signup with devise Rails

但是基本上,代码是:

class Users::RegistrationsController < Devise::RegistrationsController
  respond_to :json

   # GET /resource/sign_up
  def new
    super
  end

  def create
    super
  end
end

和我的注册表格:

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :first_name, required: true, autofocus: true, label: "Prénom" %>
    <%= f.input :last_name, required: true, label: "Nom" %>

    <!-- Lots of fields here -->

    <%= f.button :submit, 'Valider' %>
  </div>
<% end %>

我想做的就是通过AJAX调用在表格顶部显示错误。

1 个答案:

答案 0 :(得分:1)

这就是我为signing_up用户使用registration_controller的方式。

class RegistrationsController < DeviseController
  prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
  prepend_before_filter :authenticate_user!, :only => [:edit, :update, :destroy]

def create
    build_resource(sign_up_params)

    if resource.save
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_up(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        expire_session_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      flash[:notice] = flash[:notice].to_a.concat resource.errors.full_messages
      respond_to do |format|
        format.js
      end
      end
    end
  end
end

还有我的表格

<%= form_for(resource, :as => devise_resource_name, :html => {:id => 'sign_up'}, :url => user_registration_path, :remote => :true) do |f| %>
<%#= devise_error_messages! %>
<%# flash.each do |key, value| %>
  # <div class="flash <%#= key %>"><%#= value %></div>
<%# end %>

在您的create.js.erb中 $(“#id_or_class”)。html(“ <​​%= resource.errors.full_messages%>”)

如果您想覆盖devise_error_message,则为reference