I have written a custom validation function in the rails model. I want to check that validation only a field is changed(in my example the field "activestatus" is changed from "active" to "inactive"). How to do that?
class Normaluser < ApplicationRecord
validate :check_on_update, :on => :update
validate :check_on_status_change :"***what to write here?***"
private
def check_on_update
if is_cyclic?
puts "hierarchy is cyclic"
errors.add(:pid,'it is cyclic')
elsif(get_height(id)+getDepth>=2)
puts "height limit exceeded"
errors.add(:pid,'height limit exceeded')
elsif count_children>=4
errors.add(:pid,'children limit exceeded')
end
puts "all is fine at update"
end
You can use ActiveModel::Dirty
if activestatus_was == 'active' && activestatus == 'inactive'
# validation logic goes here
end
More info: https://api.rubyonrails.org/classes/ActiveModel/Dirty.html
Hope that helps!
Have a look at ActiveModel::Dirty
. To only run the validation when activestatus
changed from active
to inactive
just add a line to custom validation method:
def check_on_update
return unless activestatus_changed?(from: 'active', to: 'inactive')
# your validation code
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With