Bang! vs No-Bang: Mastering Rails Active Record Methods

The one-character difference that separates silent failures from loud exceptions – and why you need to care.

What’s the Difference?

Rails Active Record methods come in pairs. The non-bang version (save, create, update) returns a falsy value or nil on failure – silently. The bang version (save!, create!, update!) raises an exception on failure – loudly.

# Non-bang: fails silently
user = User.new(email: nil)
user.save # => false (email validation failed, no exception)
# Bang: fails loudly
user.save! # => raises ActiveRecord::RecordInvalid
# "Validation failed: Email can't be blank"

One character. Completely different failure contract.

Core Method Pairs

save / save!

The most common pair you’ll reach for.

# Non-bang: returns true/false
def update_profile(user, params)
if user.update(params)
render json: { status: :ok }
else
render json: { errors: user.errors.full_messages }, status: :unprocessable_entity
end
end
# Bang: raises on failure - use inside transactions or background jobs
def sync_user_data!(user, external_data)
user.update!(
name: external_data[:name],
synced_at: Time.current
)
end

create / create!

# Non-bang: returns the object regardless - even if invalid!
user = User.create(email: "bad")
user.persisted? # => false - object was NOT saved
user.errors.full_messages # => ["Email is invalid"]
# Bang: raises ActiveRecord::RecordInvalid immediately
user = User.create!(email: "bad")
# => ActiveRecord::RecordInvalid: Validation failed: Email is invalid

Common trap: Developers check user.id.present? after create – prefer user.persisted? instead.

update / update!

# Non-bang: returns true/false
order.update(status: "shipped") # => true or false
# Bang: raises ActiveRecord::RecordInvalid
order.update!(status: "shipped") # raises if validations fail

destroy / destroy!

# Non-bang: returns the frozen object (even if callbacks prevented destroy)
user.destroy # => returns user object, check user.destroyed? to verify
# Bang: raises ActiveRecord::RecordNotDestroyed if a before_destroy callback halts it
user.destroy! # => raises if any callback returns false/throws :abort

Finder Method Pairs

find_by / find_by!

# Non-bang: returns nil if not found
user = User.find_by(email: "alice@example.com")
return if user.nil? # handle the nil case
# Bang: raises ActiveRecord::RecordNotFound
user = User.find_by!(email: "alice@example.com")
# No nil check needed - exception propagates (caught by rescue_from in controllers)

find (no bang) already raises RecordNotFound – it’s the original “loud” finder. find_by was the “soft” alternative added later.

first_or_create / first_or_create!

# Non-bang: silently returns invalid object if creation fails
tag = Tag.where(name: "rails").first_or_create(color: nil) # may return unpersisted record
# Bang: raises if creation fails validations
tag = Tag.where(name: "rails").first_or_create!(color: "#CC0000")

create_or_find_by / create_or_find_by! (Rails 6+)

Handles race conditions in concurrent environments – tries to create, rescues the unique constraint violation, then finds.

# Non-bang
subscription = Subscription.create_or_find_by(user: current_user, plan: "pro")
# Bang - raises if found record doesn't exist and creation fails for non-uniqueness reasons
subscription = Subscription.create_or_find_by!(user: current_user, plan: "pro")

find_sole_by (Rails 7+, available in Rails 8)

# Raises ActiveRecord::RecordNotFound if zero found
# Raises ActiveRecord::SoleRecordExceeded if more than one found
admin = User.find_sole_by(role: "super_admin")

No non-bang counterpart – this is intentionally strict. It’s the “I expect exactly one” finder.

Bulk Insert Pairs (Rails 6+, fully stable in Rails 8)

These skip callbacks and validations by design – the bang variant enforces uniqueness constraints at the DB level.

# insert_all: ignores conflicts (duplicate unique keys are skipped)
Product.insert_all([
{ sku: "ABC", name: "Widget" },
{ sku: "ABC", name: "Duplicate" } # silently skipped
])
# insert_all!: raises ActiveRecord::RecordNotUnique on conflicts
Product.insert_all!([
{ sku: "ABC", name: "Widget" },
{ sku: "ABC", name: "Duplicate" } # => raises!
])
# upsert_all: updates on conflict (no bang needed for this use case)
Product.upsert_all(
[{ sku: "ABC", name: "Updated Widget" }],
unique_by: :sku
)

When to Use Each – Real Developer Scenarios

Use non-bang when:

1. Handling user input in controllers – you want to return validation errors, not crash:

def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: "Post created"
else
render :new, status: :unprocessable_entity # show errors to user
end
end

2. Conditional logic where failure is expected:

# Trying to "claim" a record in a concurrent system
if order.update(claimed_by: current_user.id, claimed_at: Time.current)
process_order(order)
else
redirect_to orders_path, alert: "Order already claimed"
end

3. Soft lookups where nil is a valid state:

promo = Promotion.find_by(code: params[:promo_code])
discount = promo&.discount_percentage || 0

Use bang when:

1. Inside database transactions – a failure must roll back everything:

ActiveRecord::Base.transaction do
order.update!(status: "processing")
inventory.update!(quantity: inventory.quantity - order.quantity)
payment.update!(charged_at: Time.current)
# If any of these fail, the whole transaction rolls back
end

2. In background jobs / service objects – let the exception bubble up to the job framework (Sidekiq, Solid Queue in Rails 8) for retry logic:

class SyncUserJob < ApplicationJob
def perform(user_id)
user = User.find(user_id) # raises if not found
user.update!(synced_at: Time.current) # raises if validation fails
# Sidekiq/Solid Queue catches the exception and retries
end
end

3. Seeds and data migrations – you want loud failures, not silent data corruption:

# db/seeds.rb
User.create!(email: "admin@example.com", role: "admin", password: "SecurePass123!")

4. In service objects where the caller handles errors:

class ChargeCustomer
def call(user, amount)
payment = Payment.create!(user: user, amount: amount, status: "pending")
result = StripeGateway.charge(user.stripe_id, amount)
payment.update!(status: "completed", stripe_id: result.id)
payment
rescue ActiveRecord::RecordInvalid => e
Rails.logger.error("Payment record invalid: #{e.message}")
raise # re-raise for the controller to handle
end
end

Quick Reference

MethodOn FailureReturns
savefalsetrue/false
save!Raises RecordInvalidtrue
createReturns unpersisted objectActiveRecord object
create!Raises RecordInvalidPersisted object
updatefalsetrue/false
update!Raises RecordInvalidtrue
destroyReturns frozen objectObject (check .destroyed?)
destroy!Raises RecordNotDestroyedObject
find_bynilObject or nil
find_by!Raises RecordNotFoundObject
insert_allSkips conflictsActiveRecord::Result
insert_all!Raises RecordNotUniqueActiveRecord::Result

The Mental Model

Think of it as a contract:

  • Non-bang – “Try this, and I’ll tell you if it worked.” You own the failure-handling logic.
  • Bang – “Do this, and if it can’t be done, raise hell.” The exception propagates to whoever is responsible for it.

A practical rule of thumb: use bang in service layers and jobs; use non-bang at the boundary where user input meets your system (controllers, form objects).

# Controller boundary - non-bang
def update
if @user.update(user_params)
...
end
end
# Service layer - bang
class UserProfileService
def sync!(user)
user.update!(last_synced: Time.current) # let it raise, job will retry
end
end

With Rails 8’s Solid Queue as the default job backend, leaning into bang methods in your jobs is even more natural – the exception bubbles up, gets logged, and the job retries based on your retry_on configuration. Silent failures in async contexts are the hardest bugs to track down.

Choose your contract deliberately. Every save without checking its return value is a bug waiting to happen.


Setup πŸ› Β Rails 8 App – Part 13: Composite keys & Candidate keys in Rails DB

πŸ”‘ What Is a Composite Key?

A composite key is a primary key made up of two or more columns that together uniquely identify a row in a table.

Use a composite key when no single column is unique on its own, but the combination is.

πŸ‘‰ Example: Composite Key in Action

Let’s say we’re building a table to track which students are enrolled in which courses.

Without Composite Key:
-- This table might allow duplicates
CREATE TABLE Enrollments (
  student_id INT,
  course_id INT
);

Nothing stops the same student from enrolling in the same course multiple times!

With Composite Key:
CREATE TABLE Enrollments (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id)
);

Now:

  • student_id alone is not unique
  • course_id alone is not unique
  • But together β†’ each (student_id, course_id) pair is unique

πŸ“Œ Why Use Composite Keys?

When to UseWhy
Tracking many-to-many relationshipsEnsures unique pairs
Bridging/junction tablese.g., students-courses, authors-books
No natural single-column keyBut the combination is unique

⚠️ Things to Keep in Mind

  • Composite keys enforce uniqueness across multiple columns.
  • They can also be used as foreign keys in other tables.
  • Some developers prefer to add an auto-increment id as the primary key insteadβ€”but that’s a design choice.

πŸ”Ž What Is a Candidate Key?

A candidate key is any column (or combination of columns) in a table that can uniquely identify each row.

  • Every table can have multiple candidate keys
  • One of them is chosen to be the primary key
  • The rest are called alternate keys

πŸ”‘ Think of candidate keys as “potential primary keys”

πŸ‘‰ Example: Users Table

CREATE TABLE Users (
  user_id INT,
  username VARCHAR(80),
  email VARCHAR(150),
  phone_number VARCHAR(30)
);

Let’s have some hands own experience in SQL queries by creating a TEST DB. Check https://railsdrop.com/2025/04/25/rails-8-app-part-13-2-test-sql-queries/

Assume:

  • user_id is unique
  • username is unique
  • email is unique
Candidate Keys:
  • user_id
  • username
  • email

You can choose any one of them as the primary key, depending on your design needs.

-- Choosing user_id as the primary key
PRIMARY KEY (user_id)

The rest (username, email) are alternate keys.

πŸ“Œ Characteristics of Candidate Keys

PropertyDescription
UniquenessMust uniquely identify each row
Non-nullCannot contain NULL values
MinimalityMust be the smallest set of columns that uniquely identifies a row (no extra columns)
No duplicatesNo two rows have the same value(s)

πŸ‘₯ Candidate Key vs Composite Key

ConceptExplanation
Candidate KeyAny unique identifier (single or multiple columns)
Composite KeyA candidate key that uses multiple columns

So: All composite keys are candidate keys, but not all candidate keys are composite.

πŸ’‘ When Designing a Database

  • Find all possible candidate keys
  • Choose one as the primary key
  • (Optional) Define other candidate keys as unique constraints
CREATE TABLE Users (
  user_id INT PRIMARY KEY,
  username VARCHAR UNIQUE,
  email VARCHAR UNIQUE
);


Let’s walk through a real-world example using a schema we are already working on: a shopping app that sells clothing for women, men, kids, and infants.

We’ll look at how candidate keys apply to real tables like Users, Products, Orders, etc.

πŸ›οΈ Example Schema: Shopping App

1. Users Table

CREATE TABLE Users (
  user_id SERIAL PRIMARY KEY,
  email VARCHAR UNIQUE,
  username VARCHAR UNIQUE,
  phone_number VARCHAR
);

Candidate Keys:

  • user_id βœ…
  • email βœ…
  • username βœ…

We chose user_id as the primary key, but both email and username could also uniquely identify a user β€” so they’re candidate keys.


2. Products Table

CREATE TABLE Products (
  product_id SERIAL PRIMARY KEY,
  sku VARCHAR UNIQUE,
  name VARCHAR,
  category VARCHAR
);

Candidate Keys:

  • product_id βœ…
  • sku βœ… (Stock Keeping Unit – a unique identifier for each product)

sku is a candidate key. We use product_id as the primary key, but you could use sku if you wanted a natural key instead.

3. Orders Table

CREATE TABLE Orders (
  order_id SERIAL PRIMARY KEY,
  user_id INT REFERENCES Users(user_id),
  order_number VARCHAR UNIQUE,
  created_at TIMESTAMP
);

Candidate Keys:

  • order_id βœ…
  • order_number βœ…

You might use order_number (e.g., "ORD-20250417-0012") for external reference and order_id internally. Both are unique identifiers = candidate keys.

4. OrderItems Table (Join Table)

This table links orders to the specific products and quantities purchased.

CREATE TABLE OrderItems (
  order_id INT,
  product_id INT,
  quantity INT,
  PRIMARY KEY (order_id, product_id),
  FOREIGN KEY (order_id) REFERENCES Orders(order_id),
  FOREIGN KEY (product_id) REFERENCES Products(product_id)
);

Candidate Key:

  • Composite key: (order_id, product_id) βœ…

Here, a combination of order_id and product_id uniquely identifies a row β€” i.e., what product was ordered in which order β€” making it a composite candidate key, and we’ve selected it as the primary key.

πŸ‘€ Summary of Candidate Keys by Table

TableCandidate KeysPrimary Key Used
Usersuser_id, email, usernameuser_id
Productsproduct_id, skuproduct_id
Ordersorder_id, order_numberorder_id
OrderItems(order_id, product_id)(order_id, product_id)

Let’s explore how to implement candidate keys in both SQL and Rails (Active Record). Since we are working on a shopping app in Rails 8, I’ll show how to enforce uniqueness and data integrity in both layers:

πŸ”Ή 1. Candidate Keys in SQL (PostgreSQL Example)

Let’s take the Users table with multiple candidate keys (email, username, and user_id).

CREATE TABLE users (
  user_id SERIAL PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  username VARCHAR(100) NOT NULL UNIQUE,
  phone_number VARCHAR(20)
);

  • user_id: chosen as the primary key
  • email and username: candidate keys, enforced via UNIQUE constraints

πŸ’Ž Composite Key Example (OrderItems)

CREATE TABLE order_items (
  order_id INT,
  product_id INT,
  quantity INT NOT NULL,
  PRIMARY KEY (order_id, product_id),
  FOREIGN KEY (order_id) REFERENCES orders(order_id),
  FOREIGN KEY (product_id) REFERENCES products(product_id)
);

This sets (order_id, product_id) as a composite candidate key and primary key.

πŸ”Έ 2. Candidate Keys in Rails (ActiveRecord)

Now let’s do the same with Rails models + migrations + validations.

βœ… users Migration (with candidate keys)

# db/migrate/xxxxxx_create_users.rb
class CreateUsers < ActiveRecord::Migration[8.0]
  def change
    create_table :users do |t|
      t.string :email, null: false
      t.string :username, null: false
      t.string :phone_number

      t.timestamps
    end

    add_index :users, :email, unique: true
    add_index :users, :username, unique: true
  end
end

βœ… User Model

class User < ApplicationRecord
  validates :email, presence: true, uniqueness: true
  validates :username, presence: true, uniqueness: true
end

βœ… These are candidate keys β€” email and username could be primary keys, but we are using id instead.

βœ… Composite Key with OrderItem (Join Table)

ActiveRecord doesn’t support composite primary keys natively, but you can enforce uniqueness via a multi-column index:

Migration:

class CreateOrderItems < ActiveRecord::Migration[8.0]
  def change
    create_table :order_items, id: false do |t|
      t.references :order, null: false, foreign_key: true
      t.references :product, null: false, foreign_key: true
      t.integer :quantity, null: false

      t.timestamps
    end

    add_index :order_items, [:order_id, :product_id], unique: true
  end
end

Model:

class OrderItem < ApplicationRecord
  belongs_to :order
  belongs_to :product

  validates :quantity, presence: true
  validates :order_id, uniqueness: { scope: :product_id }
end

🎯 This simulates a composite key behavior: each product can only appear once per order.

βž• Extra: Use composite_primary_keys Gem (Optional)

If you really need true composite primary keys, use:

gem 'composite_primary_keys'

But it’s best to avoid unless your use case demands it β€” most Rails apps use a surrogate key (id) for simplicity.


to be continued.. πŸš€