ruby
22 lines · 7 steps
Enforcing order-item integrity in Rails
A migration and model that guard order-item data at both the database and application layers.
Explained by
highlit
1class CreateOrderItems < ActiveRecord::Migration[7.1]
2 def change
3 create_table :order_items do |t|
4 t.references :order, null: false, foreign_key: { on_delete: :cascade }
5 t.references :product, null: false, foreign_key: true
6 t.integer :quantity, null: false, default: 1
7 t.decimal :unit_price, precision: 10, scale: 2, null: false
8
9 t.timestamps
10 end
11
12 add_check_constraint :order_items, "quantity > 0", name: "quantity_positive"
13 end
14end
15
16class OrderItem < ApplicationRecord
17 belongs_to :order
18 belongs_to :product
19
20 validates :quantity, numericality: { greater_than: 0 }
21 validates :unit_price, numericality: { greater_than_or_equal_to: 0 }
22end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Database constraints and model validations are complementary defenses, not redundant ones.
- 2Cascading foreign keys let the database clean up dependent rows automatically when a parent is deleted.
- 3Check constraints enforce business rules like positivity even against writes that bypass the model.
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/enforcing-order-item-integrity-in-rails-explained-ruby-1ec3/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.