A
A
Alexander2016-01-21 05:52:18
Ruby on Rails
Alexander, 2016-01-21 05:52:18

How to prioritize validations in Ruby on Rails?

validates_presence_of :count
validates :count, numericality: true
validates :count, numericality: { only_integer: true,greater_than: 0}

validate :validate_max_count_sklad_tovar

I set two validations, the second one, which I created, is performed from the very beginning, but it is necessary that after the first one in the list. How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vsuhachev, 2016-01-21
@vsuhachev

No way. Your code should not be tied to the order of validations. Inside validate_max_count_sklad_product check if count is a number and only then check against the warehouse.

A
Alexander, 2016-01-21
@savio

Did it like this:

class InetSklad < ActiveRecord::Base

  validates :tovar_id, presence: true
  validates :count, presence: true
  validates :count, numericality: true
  validates :count, numericality: { only_integer: true,greater_than: 0}
  
  validate :validate_max_count_sklad_tovar, :if => Proc.new { |a| a.dependent_attributes_valid? }

def dependent_attributes_valid?
    [:tovar_id, :count].each do |field|
      self.class.validators_on(field).each { |v| v.validate(self) }
      if self.errors.messages[field].present?
        self.errors.messages[field]=[self.errors.messages[field][0]] if self.errors.messages[field].kind_of?(Array)
        return false
      end
    end
    return true
  end

works!
spied here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question