Zack Herbert
Zack Herbert

Reputation: 960

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 :)

Upvotes: 0

Views: 990

Answers (3)

Dharam Gollapudi
Dharam Gollapudi

Reputation: 6438

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.

Upvotes: 0

eugen
eugen

Reputation: 9226

This might work:

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

Upvotes: 1

Oleh  Sobchuk
Oleh Sobchuk

Reputation: 3722

use if like attribute, not like condition:

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

Upvotes: 3

Related Questions