Post

Ruby on Rails: Enforcing “All or None” Field Presence with Conditional Validations

Ruby on Rails: Enforcing “All or None” Field Presence with Conditional Validations

Understanding the Requirement

Let’s say we have a Payment model with the following attributes:

  • account_number
  • routing_number
  • swift_code

We want to enforce that if any one of these fields is present, then all of them should be present.

We can’t have only the routing number, for example; we need all of the payment details. However, if someone chooses to enter their details at a later time, we don’t want to enforce this validation immediately.

Implementing the Validation

To implement this validation, you can use a conditional validator in your Rails model. Here’s how you can do it:

1
2
3
class Payment < ApplicationRecord
  validates_presence_of :account_number, :routing_number, :swift_code, if: -> { account_number.present? || routing_number.present? || swift_code.present? }
end

In this example, the validates_presence_of method ensures that the account_number, routing_number, and swift_code fields are validated for presence, but only if any one of them is present. This is controlled by the if option, which takes a lambda that returns true if any of the fields are present.

Conclusion

That’s it — pretty simple. By using conditional validations with validates_presence_of, we can ensure that all required payment fields are completed together if any are provided. This method utilizes Rails’ built-in validation tools effectively, keeping the model code clean, maintainable, and straightforward.

This post is licensed under CC BY-NC 4.0 by the author.