Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: validating a field is present only if another is present

I have a model where there are two fields that can technically be null. The field names are :is_activated and :activated_at. :activated_at is only required if :is_activated is set to true. It does not need to be present if :is_activated is false. What's the appropriate way in Rails to set this validation directly into ActiveRecord?

like image 516
randombits Avatar asked Dec 06 '12 18:12

randombits


1 Answers

You can use a Proc on the :activated_at validator.

validates :activated_at, :presence, if: Proc.new { |a| a.is_activated? }

Recommended Reading:

  • http://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless
  • http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

Finally, you should consider renaming :is_activated to simply :activated. This is considered better practice in Rails. The is_ prefix is used in other languages for boolean attributes because their method names don't support a ? character. Ruby does, and Rails generates ___? methods on boolean attributes. Because of this it's better to just call the attribute :activated and check it with activated?.

like image 179
deefour Avatar answered Oct 16 '22 22:10

deefour