Zack Herbert February 2016

Rails Validation based on presence of some attribute

Trying to create a validation on a model. The model has two attributes private_key and public_key. If the user provides either one I want the validation to make sure that the other is provided. So if they provide the public_key they must provide the private_key and vice versa. Right now I have the following:

validates_presence_of :public_key if :private_key?
validates_presence_of :private_key if :public_public?

For some reason if I don't provide either I am getting an error.

Thanks in advance :)

Answers


Oleg Sobchuk February 2016

use if like attribute, not like condition:

validates_presence_of :public_key, if: :private_key?
validates_presence_of :private_key, if: :public_public?


eugen February 2016

This might work:

validates_presence_of :public_key, if: 'private_key?'
validates_presence_of :private_key, if: 'public_public?'


Dharam February 2016

You could also use validates shortcut method, which allows you to tuck in multiple validations later on the same attribute if needed:

validates :public_key, presence: true, if: Proc.new { |r| r.private_key.present? }
validates :private_key, presence: true, if: Proc.new { |r| r.public_key.present? }

I would prefer to test the presence of an attribute explicitly, for example using public_key.present? rather than public_key? as it is more readable and AFAIK public_key? method is only available for boolean fields, unless you defined.

Post Status

Asked in February 2016
Viewed 1,249 times
Voted 12
Answered 3 times

Search




Leave an answer