我希望将一些数据与错误一起发送。我猜它在响应者的某个地方,虽然不知道从哪里开始。从本质上讲,我想做
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" }
}
如果出现错误,可以发送数据吗?
答案 0 :(得分:0)
# 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,每个错误都可以访问此访问者。 有关扩展代码的更多功能。