Tetiana Chupryna
Tetiana Chupryna

Reputation: 1074

Rails skip other validations if one fails

I need a help with Rails ActiveRecord validations.

I have a model with some validations on different fields:

class MyModel < ActiveRecord::Base
  validate :custom_validation
  validates :field1, :field2, presence: true
  validates :field3, uniqueness: true

  def custom_validation
   # if condition
   #   errors.add(:field4, 'error message')
   # end
  end
end

I need skip validations on field1, field2, field3 if custom_validation fails. I know that I can do this just to add condition on validations of field1, field2 and field3:

validates: field1, field2, presence: true, if: custom_validation

However this solution seems to me a bit ugly and I want something more DRY. Is it possible?

I'm thankful for any help!

Upvotes: 4

Views: 2421

Answers (1)

max
max

Reputation: 102443

I don't really see how you would do that without overriding the built in rails validations. The crux is that the validations are declared when the class is loaded and not in the instance.

The alternative to using if: :custom_validation on all of your validation could perhaps be to override the valid? method and remove the errors for the other keys:

def valid?(context = nil)
  super
  if errors.key?(:field4)
    errors.keys.each {|k| errors.delete(k) unless k == :field4 }
  end
  errors.empty?
end

Upvotes: 2

Related Questions