Active Record Validations in Ruby on Rails: grouping conditional validations

Gonzalo Galdámez
Unagi
Published in
2 min readApr 18, 2024
Active Record Validations in Ruby on Rails: grouping conditional validations

Ruby on Rails includes a variety of built-in validation options. However, some advanced features, such as grouping conditional validations using with_options, may still be unfamiliar to many. In this article, we aim to shed light on this technique.

What are conditional validations in Ruby on Rails?

Conditional validations allow you to apply validation rules based on certain conditions being met. Sometimes it is useful to have multiple validations using one condition, which can be easily achieved using with_options.

Example

Let’s imagine we’re developing an e-commerce platform where users can leave reviews for products. However, we want to enforce stricter validation rules for reviews that have been approved by administrators. Let’s see how we can achieve this using Ruby on Rails’ Active Record Validations.

class Review < ApplicationRecord
with_options if: :is_approved? do |approved_review|
approved_review.validates :content, presence: true, length: { minimum: 50 }
approved_review.validates :rating, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 10 }
end

private

def is_approved?
# Implementation to determine if the review has been approved by an admin
end
end

In the code above, we define a Review model with two conditional validations grouped using with_options. The is_approved? method serves as the condition for applying these validations. When a review is approved (as determined by the is_approved? method), the validations for content and rating will be enforced, ensuring that approved reviews meet stricter criteria, including a minimum content length (50 chars) and a valid rating (1-10).

By grouping conditional validations using with_options we can make our code more readable and expressive by clearly defining when certain validation rules should apply. We are also organizing validations into logical groups based on conditions.

Conditional validations offer a powerful mechanism for applying validation rules selectively in Ruby on Rails applications. Features like with_options allow us to group validations based on conditions, leading to cleaner, more maintainable code.

Unagi provides software development services in #Ruby and #JavaScript, a stack we still choose after +11 years. Check out more about us.

--

--