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
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 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.