简体   繁体   中英

How to use ActiveModel's Validations & Callbacks on a custom class?

I am trying to use ActiveModel Validations & Callbacks on custom class.

class TestClass
  include ActiveModel::Validations
  define_model_callbacks :validate

  attr_accessor :test_field
  validates :test_field, presence: true # THIS IS CAUSING ISSUES!

  before_validate do 
    test_field.try('upcase!')
  end

  def custom_validate!
    run_callbacks :validate do
      puts "Done"
    end
  end
end

But I am receiving the following error:

Failure/Error:
  run_callbacks :validate do
    ...
  end
  NoMethodError: 
     undefined method `before_validate' for #<ActiveModel::Validations::PresenceValidator>

If I change callback name to something else than validate (eg validate_x ) it works. Apparently validate is doing a bit more than I would expect. This error only happens if validates :test_field, presence: true is defined. For custom before_validate {} blocks it doesn't raise errors. Any idea how to fix this?

The callback name is before_validation , just include ActiveModel::Validations::Callbacks module too, try this

include ActiveModel::Validations
include ActiveModel::Validations::Callbacks

before_validation do 
  test_field.try('upcase!')
end

To run custom validation

before_validation :custom_validation

https://api.rubyonrails.org/classes/ActiveModel/Validations/Callbacks/ClassMethods.html#method-i-before_validation

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM