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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Database constraints and model validations are complementary defenses, not redundant ones.
  2. 2Cascading foreign keys let the database clean up dependent rows automatically when a parent is deleted.
  3. 3Check constraints enforce business rules like positivity even against writes that bypass the model.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Enforcing order-item integrity in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code