Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails update validation only when specific field value is changed

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 
like image 471
code0079 Avatar asked Sep 06 '25 03:09

code0079


2 Answers

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!

like image 87
Rajdeep Singh Avatar answered Sep 07 '25 23:09

Rajdeep Singh


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
like image 36
spickermann Avatar answered Sep 07 '25 21:09

spickermann