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
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 Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
ruby
require "csv" def parse_transaction_row(line) fields = CSV.parse_line(line, headers: false, skip_blanks: true)
Parsing one CSV transaction row in Ruby
parsing
type-coercion
error-handling
Intermediate
6 steps
ruby
class NewCommentNotifier < ApplicationNotifier deliver_by :database deliver_by :email do |config|
Multi-channel notifications with Noticed in Rails
notifications
delivery-methods
fan-out
Intermediate
6 steps
ruby
class DocumentsController < ApplicationController before_action :authenticate_user! before_action :set_document
Serving secure file downloads in Rails
authorization
signed-urls
active-storage
Intermediate
8 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.