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
class DashboardMetrics CACHE_TTL = 15.minutes def initialize(account)
Caching dashboard metrics in Rails
caching
service-object
query-optimization
Intermediate
5 steps
ruby
class LRUCache def initialize(capacity) raise ArgumentError, "capacity must be positive" unless capacity.positive?
How an LRU cache works in Ruby
caching
eviction
hash-ordering
Intermediate
7 steps
ruby
class QueryParser def self.parse(query_string) new(query_string).parse end
Parsing nested query strings in Ruby
parsing
recursion
tokenization
Intermediate
9 steps
ruby
class Article < ApplicationRecord belongs_to :author, class_name: "User" has_many :taggings, dependent: :destroy has_many :tags, through: :taggings
How scopes compose in Rails
scopes
activerecord
query-composition
Intermediate
8 steps
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
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.