123
123

Reputation: 794

Rails Validation on presence of two or more entities

I've got two columns by name,

product_available_count (integer) and product_available_on (date).

I need to perform a model level validation on these columns.

The validation should check that if product_required is true then either of fields should be populated.

When a Product Manager fill in the catalogue, we need to perform a model level validation that checks that he should fill in either of the fields.

Suggest me any elegant way of writing a custom validation for my requirement.

I've tried this approach

validates :product_available_count_or_product_available_on if product_required?

def product_available_count_or_product_available_on
  //logic ???
end

Is Custom validation the only way forward to my requirement. Can I use Proc or any other approach to write a better code.

Upvotes: 0

Views: 115

Answers (1)

Anil Maurya
Anil Maurya

Reputation: 2328

I think Custom validation is best approach for this kind of problem

validate :product_available_count_or_product_available_on if product_required?

def product_available_count_or_product_available_on
  if [product_available_count, product_available_on].compact.blank.size == 0
    errors[:base] << ("Please select alteast one.")
  end
end      

but if you really donot want to write custom validation then try this

validates :product_available_count, :presence => { :if =>  product_required? && product_available_on.blank? }
validates :product_available_on, :presence => { :if =>  product_required? && product_available_count.blank? }

Upvotes: 1

Related Questions