ruby 42 lines · 8 steps

Validating registrations in Rails

A Rails model layers built-in and custom validations, then turns the resulting errors into localized, human-readable output.

Explained by highlit
1class Registration < ApplicationRecord
2 belongs_to :event
3 
4 validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
5 validates :seats, numericality: { greater_than: 0, less_than_or_equal_to: 10 }
6 validate :event_not_sold_out
7 
8 def confirmation_summary
9 return I18n.t("registrations.summary.invalid") if errors.any?
10 
11 I18n.t(
12 "registrations.summary.confirmed",
13 email: email,
14 seats: seats,
15 event: event.title
16 )
17 end
18 
19 def localized_error_report
20 errors.map do |error|
21 {
22 attribute: self.class.human_attribute_name(error.attribute),
23 message: error.full_message,
24 raw: error.message
25 }
26 end
27 end
28 
29 private
30 
31 def event_not_sold_out
32 return if event.blank? || seats.blank?
33 
34 if event.available_seats < seats
35 errors.add(
36 :seats,
37 :exceeds_availability,
38 count: event.available_seats
39 )
40 end
41 end
42end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Combining declarative validators with a custom method keeps simple rules terse while allowing domain logic like seat availability.
  2. 2Rails' errors collection carries structured data you can reshape for APIs or localized display.
  3. 3Guarding on blank associations before custom checks avoids nil errors when other validations already failed.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating registrations in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code