Rails 4 ajax:除非首先触发ajax:success,否则错误不会触发

时间:2014-11-25 05:10:01

标签: ruby-on-rails-4 ujs

在尝试使用AJAX加载ActiveRecord验证错误时,我无法弄清楚我做错了什么。除非我已经提交了一个有效的表单并触发了ajax:success,否则我无法获取ajax:error错误。我曾尝试仅绑定ajax:error以查看成功是否可能阻止它。我已阅读working with javascript in rails上的rails文档,并用Google搜索我的问题无济于事。我曾尝试同时使用.bind()和.on(),但我没有看到任何区别。我确信有一些非常简单的东西让我失踪,但我一直在看这个太久了,而且我似乎无处可去。

这是代码。

模型

class User < ActiveRecord::Base
  before_create :set_activation_key
  before_save :encrypt_password
  before_save :downcase_username
  after_save :clear_password

  validates :username,
            format: {
                with: /\A.*\z/,
                message: 'invalid'
            },
            uniqueness: {message: 'already in use'},
            presence: {message: 'cannot be blank'}

  validates :email_address,
            format: {
                with: /\A.+@.+\..+\z/,
                message: 'invalid'
            },
            uniqueness: {message: 'already in use'},
            presence: {message: 'cannot be blank'}


  validates :password, :confirmation => true, 
            presence: {message: 'cannot be blank'},
            length: {:within => 6..20,
                     :too_long => 'too long',
                     :too_short => 'too short',
            }

  def encrypt_password
    if password.present?
      self.salt = BCrypt::Engine.generate_salt
      self.password = BCrypt::Engine.hash_secret(password, salt)
    end
  end

  def clear_password
    self.password = nil
  end

  def set_activation_key
    self.activation_key = SecureRandom.urlsafe_base64
  end

  def downcase_username
    self.username = self.username.downcase
  end

  def self.authenticate(username, password)
    user = User.find_by_username(username.to_s.downcase)
    if user && user.password == BCrypt::Engine.hash_secret(password, user.salt)
      user
    else
      nil
    end
  end
end

控制器

class Users::UsersController < ApplicationController

  # GET /register
  def new
    @user = User.new
  end

  # POST /users
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        UserMailer.registration_email(@user.email_address).deliver
        format.html { redirect_to root_path, notice: 'Check your email' }
        format.js
      else
        format.html { render action: 'new' }
        format.js { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def user_params
    params.require(:user).permit(:username, :email_address, :password, :password_confirmation)
  end
end

部分

<%= form_for User.new, remote: true do |f| %>
    <div id="registration_messages"></div>
    <div id="registration_errors"></div>
    <%= f.label :username %>
    <%= f.text_field :username%>

    <%= f.label :email_address %>
    <%= f.text_field :email_address %>

    <%= f.label :password %>
    <%= f.password_field :password %>

    <%= f.label :password_confirmation, 'Confirm Password' %>
    <%= f.password_field :password_confirmation %>

    <%= f.submit 'Register', :class => 'tiny button' %>
    <a class="close-reveal-modal">&#215;</a>
<% end %>

create.js.erb

$(document).ready(function() {
    $('#new_user')
            .bind("ajax:success", function(event, data, xhr, status){
                var $form = $(this);
                $form.find('input[type=text], input[type=password], textarea').val('');
                $("div#registration_messages").append('<div data-alert class="alert-box success">Check your email</div>');
            }).bind("ajax:error", function(event, data, xhr, error){
                console.log(event);
                console.log(data);
                console.log(xhr);
                console.log(error);
                alert("ajax:error");
            });
});

1 个答案:

答案 0 :(得分:4)

这对您当前的技术没有帮助,但您可以尝试在纯JQuery中执行此操作并抛弃js.erb文件。一旦掌握了它,我总会发现这种方式更直接。我希望以下代码不会产生你所看到的问题。

<强>控制器

# POST /users
def create
  @user = User.new(user_params)

  respond_to do |format|
    if @user.save
      UserMailer.registration_email(@user.email_address).deliver
      format.html { redirect_to root_path, notice: 'Check your email' }
      format.js { render nothing: true, status: :created }
    else
      format.html { render action: 'new' }
      format.js { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

<强> javascript.js

  # could go in application.js while you're testing it, but best to factor it out into it's own file.
  $('form#new_user').on('ajax:success', function(event, data, xhr, status) {
    var $form = $(this);
    $form.find('input[type=text], input[type=password], textarea').val('');
    $("div#registration_messages").append('<div data-alert class="alert-box success">Check your email</div>');
  });
  $('form#new_user').on('ajax:error', function(event, data, xhr, status) {
    console.log(event);
    console.log(data);
    console.log(xhr);
    console.log(error);
    alert("ajax:error");
  });