Ruby on rails 4 rails4ajax:error除非首先触发了ajax:success,否则不会触发

Ruby on rails 4 rails4ajax:error除非首先触发了ajax:success,否则不会触发,ruby-on-rails-4,ujs,Ruby On Rails 4,Ujs,当我试图用AJAX加载ActiveRecord验证错误时,我无法找出我做得不对的地方。我无法触发ajax:error,除非我已经提交了一个有效的表单并触发了ajax:success。我只尝试绑定ajax:error,看看成功是否会阻止它。我已经阅读了上的rails文档,并在Google上搜索了我的问题,但没有结果。我尝试过使用.bind和.on,但我没有看到任何区别。我确信我遗漏了一些非常简单的东西,但我已经看了太久了,我似乎没有取得任何进展 这是代码 模型 控制器 局部的 create.js.

当我试图用AJAX加载ActiveRecord验证错误时,我无法找出我做得不对的地方。我无法触发ajax:error,除非我已经提交了一个有效的表单并触发了ajax:success。我只尝试绑定ajax:error,看看成功是否会阻止它。我已经阅读了上的rails文档,并在Google上搜索了我的问题,但没有结果。我尝试过使用.bind和.on,但我没有看到任何区别。我确信我遗漏了一些非常简单的东西,但我已经看了太久了,我似乎没有取得任何进展

这是代码

模型

控制器

局部的

create.js.erb


这对您当前的技术没有帮助,但您可以尝试在纯JQuery中进行,并放弃js.erb文件。我总是发现,一旦你掌握了窍门,这种方法就更简单了。我希望下面的代码不会产生您看到的问题

控制器

javascript.js


我对Rails/Ajax这个品牌不太熟悉,但我想知道在response_中调用'render'to block's else是否会阻止它加载部分内容。尝试删除render json:@user.errors,然后看看它是否有效。我怀疑同样的事情,但我还没有找到一种方法让它有效。我不能直接删除渲染。我刚刚尝试删除它,但出现了其他错误。我现在不在我的开发机器上,所以我不记得昨晚到底发生了什么。我知道简单地移除它并不能产生预期的结果。我将通读一遍,看看是否能从中找到解决方案。“另一种方式”是什么?您是否将其放在application.js文件中?我不会将其放在application.js中,但会放在其他javascript文件中。我发现这种方式比Rails方式更常见。这确实有效!我还是不太明白为什么轨道不起作用。我使用了{render json:@user.errors…},这当然是问题的一部分。我现在打算使用这个解决方案,但我想知道为什么rails版本对我不起作用。我现在感觉更确定的是,通过在响应块中调用render,您正在覆盖rails默认的渲染操作,该操作会渲染相应的js.erb模板。在这里看到公认的答案:没问题!看起来您还可以显式地告诉format.js呈现js.erb模板。请参见此处的答案:。这也可以让您传递您的状态,如render path/to/create.js.erb,status:422
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 %>
$(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");
            });
});
# 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
  # 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");
  });