ActiveRecord - replace model validation error with warning

后端 未结 3 1027
滥情空心
滥情空心 2021-02-04 12:51

I want to be able to replace a field error with a warning when saving/updating a model in rails. Basically I want to just write a wrapper around the validation methods that\'ll

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 13:23

    The validation_scopes gem uses some nice metaprogramming magic to give you all of the usual functionality of validations and ActiveRecord::Errors objects in contexts other than object.errors.

    For example, you can say:

    validation_scope :warnings do |s|
      s.validates_presence_of :some_attr
    end
    

    The above validation will be triggered as usual on object.valid?, but won't block saves to the database on object.save if some_attr is not present. Any associated ActiveRecord::Errors objects will be found in object.warnings.

    Validations specified in the usual manner without a scope will still behave as expected, blocking database saves and assigning error objects to object.errors.

    The author has a brief description of the gem's development on his blog.

提交回复
热议问题