将通用(未绑定到键或字段)错误消息添加到 rails FormObject

Add a generic (not bound to a key nor field) error message to rails FormObject

我有以下 ruby class:

class MyFormObject < FormObject
  attribute :some_field

  validates :some_field, presence: true
  validate :my_custom_validation

  def my_custom_validation
    errors.add "Do_not_have_key","This error message is self contained, not linked to any field and no field prefix required"
  end
end

我想执行我的自定义验证逻辑。将错误添加到错误集合中,但其中一些 未绑定到任何键或字段。假设它们取决于执行验证时月球的位置:)

我也想当其他人使用我的 class 并呼叫:

errors.full_messages

要获得在所有错误前面附加错误键的默认行为,需要 "generic"/"not bound to a field" 个。

是否有优雅的方式来实现这种行为?并关闭此 class 中的 solution/workaround 并且所有消费者都不知道存在 "special" 错误?

根据此处的 Rails 文档:https://guides.rubyonrails.org/active_record_validations.html#errors-base

You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since errors[:base] is an array, you can simply add a string to it and it will be used as an error message.

因此在您的情况下,您的验证器变为:

def my_custom_validation
  errors[:base] << "Your error message here."
end