0

我希望将一些数据与错误一起发送。我猜它在响应者的某个地方,虽然不知道从哪里开始。本质上,我想做

model.errors.add :some_attr, "error message"
model.also_send_attrs = { prop: "some data also sent" }

并且结构是通常的(有一些附加)

{ 
  errors: { some_attr: ['error message'] },
  also_send_data: { prop: "some data also sent" }
}

如果发生错误,是否可以在错误的同时发送数据?

4

1 回答 1

0

嗯,扩展 Rails。

# config/initializers/also_send_attrs.rb

module AlsoSendAttrs
  module ErrorsExtension
    extend ActiveSupport::Concern
    included do
      delegate :also_send_attrs, :to => :@base
    end
  end

  module ActiveRecordExtension
    extend ActiveSupport::Concern
    included do
      attr_accessor :also_send_attrs
    end
  end

  ActiveModel::Errors.send(:include, ErrorsExtension)
  ActiveSupport.on_load :active_record do
    include ActiveRecordExtension
  end
end

这是一种基本方法。

每个模型都有一个访问器 :also_send_attrs 并且每个错误都可以访问这个访问器。如需更多功能,请扩展代码。

于 2012-12-12T22:05:21.913 回答