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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Combining declarative validators with a custom method keeps simple rules terse while allowing domain logic like seat availability.
- 2Rails' errors collection carries structured data you can reshape for APIs or localized display.
- 3Guarding on blank associations before custom checks avoids nil errors when other validations already failed.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
ruby
require "csv" def parse_transaction_row(line) fields = CSV.parse_line(line, headers: false, skip_blanks: true)
Parsing one CSV transaction row in Ruby
parsing
type-coercion
error-handling
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/validating-registrations-in-rails-explained-ruby-83df/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.