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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Custom validations let you enforce business rules that built-in validators can't express.
  2. 2Guarding against blank values inside a validator avoids piling redundant errors on missing fields.
  3. 3Scopes package common query conditions into reusable, chainable named methods.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Guarding booking dates in a Rails model — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code