ActiveAdmin打破了Rails JQuery UJS。不引人注目的JavaScript ajax:成功和ajax:错误没有触发或被调用

时间:2018-06-08 03:05:22

标签: javascript jquery ruby-on-rails activeadmin rails-ujs

我有以下

=form_for @issue, remote: true, html: {class: 'form-inline'} do |f|
  ...

<form class="form-inline" id="new_issue" action="/issues" accept-charset="UTF-8" data-remote="true" method="post">

$(document).on 'turbolinks:load', ->
  $("#new_issue").on("ajax:success", (e, data, status, xhr) ->
    console.log 'data='+data
    console.log 'status='+status
    console.log 'xhr='+xhr
    $("#new_issue_success").append(xhr.responseText).show()
    $("#new_issue_error").hide()
  ).on("ajax:error", (e, xhr, status, error) ->
    console.log 'error='+error
    console.log 'status='+status
    console.log 'xhr='+xhr
    $("#new_issue_error").append("ERROR: #{error}").show()
    $("#new_issue_success").hide()
  ).on('ajax:complete', ->
    console.log 'complete'
  )

  def create
    issue = Issue.new issue_params
    issue.validate_user_entry
    if issue.errors.empty? && issue.save # can't use #valid? because that clears errors and runs only standard Rails validations!
      render json: issue, status: :created
    else
      render json: issue.errors.full_messages, status: :unprocessable_entity
    end

我在浏览器控制台中看到了这个

POST http://localhost:3000/issues 422 (Unprocessable Entity)
XHR failed loading: POST "http://localhost:3000/issues".

这在我的Rails服务器控制台中

Started POST "/issues" for 127.0.0.1 at 2018-06-07 22:29:34 -0400
Processing by IssuesController#create as JS
  Parameters: {"utf8"=>"√", "issue"=>{"first_name"=>"", "last_name"=>"", "city"=>"", "issue"=>""}, "commit"=>"Submit"}
Completed 422 Unprocessable Entity in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms)

那么为什么不调用Ajax回调并在控制台上打印出结果呢?无论是成功还是失败,我都希望它能够显示结果。

直接从指南中获取:http://guides.rubyonrails.org/v5.0/working_with_javascript_in_rails.html#form-for

我也试过

$(document).on("ajax:success", (e, data, status, xhr) ->
  ...
).on "ajax:error", (e, xhr, status, error) ->
  ...

我确认事件正在侦听浏览器中的元素

enter image description here

我在另一个有效的Rails项目中有类似的东西。我像其他项目一样降级到Rails 5.0.6,但没有帮助。

Rails 5.0.7,JQuery 3.3.1

我发现这是由ActiveAdmin引起的。我有entered a bug for it。当我将active_admin.js.coffee重命名为active_admin.js.coffee.xxx时,它可以正常工作,但当然会中断ActiveAdmin。我尝试将//= stub active_admin添加到application.js,但由于某种原因jquery_ujs无法加载。我查看了网页的来源,/assets/jquery_ujs.self-784...将不再显示,尽管//= require jquery_ujs位于application.js

我如何同时拥有ActiveAdmin和UJS?我/admin页面上不需要UJS。

1 个答案:

答案 0 :(得分:2)

我通过将active_admin.js.coffee移至vendor\assets\javascripts\active_admin.js.coffee来修复此问题。现在/admin正常工作,/的远程表单正常工作。根本不明显。希望他们把它放在文档中,或者更好,只是不要干扰标准的Rails。