ruby
19 lines · 5 steps
Guarding booking dates in a Rails model
A Booking model layers associations, presence checks, and a custom validation to keep date ranges valid.
Explained by
highlit
1class Booking < ApplicationRecord
2 belongs_to :room
3 belongs_to :guest
4
5 validates :starts_on, :ends_on, presence: true
6 validate :ends_on_after_starts_on
7
8 scope :active, -> { where(status: :confirmed) }
9
10 private
11
12 def ends_on_after_starts_on
13 return if starts_on.blank? || ends_on.blank?
14
15 if ends_on <= starts_on
16 errors.add(:ends_on, :after_start, message: "must be after the start date")
17 end
18 end
19end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Custom validations let you enforce business rules that built-in validators can't express.
- 2Guarding against blank values inside a validator avoids piling redundant errors on missing fields.
- 3Scopes package common query conditions into reusable, chainable named methods.
Related explainers
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
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
Intermediate
9 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/guarding-booking-dates-in-a-rails-model-explained-ruby-fb07/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.