【问题标题】:Backbone Error Callback with Rails 4 Controller Response [duplicate]Rails 4控制器响应的骨干错误回调[重复]
【发布时间】:2014-08-28 21:51:46
【问题描述】:

我有一个主干应用程序,已集成到我的 rails 应用程序中。我正在尝试将我的验证错误传递回创建时的主干模型,但它并没有一直返回到主干。

这是我的模型:

# app/assets/javascripts/models/source.js.coffee
class MyApp.Models.Source extends Backbone.Model
  urlRoot: '/api/sources'

还有我的 Rails 控制器:

# app/controller/api/sources_controller.rb
class Api::SourcesController < ApplicationController
  respond_to :json

  def create
    @source = Source.new source_params

    if @source.save
      respond_with @source
    else
      render json: { error: @source.error.messages }, status: 422
    end
  end

  def source_params
    params.require(:source).permit(:feed_id, :source, :term)
  end
end

最后是尝试创建我的模型的代码:

# app/assets/javascripts/views/new_source.js.coffee
class MyApp.Views.SourceForm extends Backbone.View
  events: ->
    'submit .new_source': 'createSource'

  createSource: ->
    @source = new Juicer.Models.Source $(event.target).serializeHash()
    @source.save
      success: =>
        console.log 'ya'
      error: =>
        console.log 'boo'

但是,当我实际运行此代码时,它永远不会一直返回到此主干回调,而是在控制台中收到此错误:

POST http://localhost:3000/api/sources 422 (Unprocessable Entity)

我在 Backbone 源代码中进行了一些研究,但我无法弄清楚为什么它没有通过。它似乎卡在 jQuery .ajax 方法上,该方法应该触发错误回调,但似乎正在中断。

我正在使用 Backbone v1.1.1 和 jQuery v1.11.1 和 Rails 4.1.5

【问题讨论】:

  • @muistooshort 我故意希望它在这种情况下失败,我希望 source.save 返回 false。如果我传入适当的参数,它工作正常。

标签: javascript jquery ruby-on-rails backbone.js ruby-on-rails-4


【解决方案1】:

如果我将 null 作为第一个参数传递给this SO 帖子,它似乎会触发错误回调

像这样:

createSource: ->
  @source = new Juicer.Models.Source $(event.target).serializeHash()
  @source.save null,
    success: =>
      console.log 'ya'
    error: =>
      console.log 'boo'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多