Skip to content

Instantly share code, notes, and snippets.

@benoittgt
Created November 27, 2024 08:54
Show Gist options
  • Save benoittgt/54511dacb690b6e47b05ff791c85757b to your computer and use it in GitHub Desktop.
Save benoittgt/54511dacb690b6e47b05ff791c85757b to your computer and use it in GitHub Desktop.
db constraint Rails demo
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "rails"
gem "pg"
end
require "active_record"
require "minitest/autorun"
require "logger"
ActiveRecord::Base.establish_connection(adapter: "postgresql", database: "playground")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :shipments, force: true do |t|
t.string :status, null: false
t.datetime :received_at
t.timestamps
t.check_constraint "(status != 'expedited' OR received_at IS NULL)",
name: 'check_expedited_not_received'
end
end
class Shipment < ActiveRecord::Base
validates :status, presence: true
end
# All good
Shipment.create!(status: 'received', received_at: Time.current)
Shipment.create!(status: 'expedited')
# Constraint
Shipment.create!(status: 'expedited', received_at: Time.current)
=begin
D, [2024-11-27T09:52:16.146151 #25801] DEBUG -- : Shipment Create (0.7ms) INSERT INTO "shipments" ("status", "received_at", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["status", "expedited"], ["received_at", "2024-11-27 08:52:16.145028"], ["created_at", "2024-11-27 08:52:16.145184"], ["updated_at", "2024-11-27 08:52:16.145184"]]
D, [2024-11-27T09:52:16.149025 #25801] DEBUG -- : TRANSACTION (2.8ms) ROLLBACK
/Users/benoit.tigeot/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/activerecord-8.0.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:162:in `exec_params': PG::CheckViolation: ERROR: new row for relation "shipments" violates check constraint "check_expedited_not_received" (ActiveRecord::StatementInvalid)
DETAIL: Failing row contains (3, expedited, 2024-11-27 08:52:16.145028, 2024-11-27 08:52:16.145184, 2024-11-27 08:52:16.145184).
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment