guest@websec ~ % man r04-models
Models and ApplicationRecord
A model is a Ruby class for one table. It owns the rules about its data: what is valid, how records relate, what states they can be in, and what JSON they show to each audience.
as_admin_json). Shared safety nets — soft delete, audit trail, secret redaction — live once in ApplicationRecord.ApplicationRecord: the parent of every model
Rails generates ApplicationRecord so you have one place to put behaviour that every model shares. It is abstract: it has no table of its own. Our version does a lot:
class ApplicationRecord < ActiveRecord::Base include SoftDeletable # deleted_at, default_scope, soft_delete!, restore primary_abstract_class # no table; the app's main DB connection has_paper_trail skip: [:authentication_token, :otp_secret] # audit history # Ransack search: only columns that don't look like secrets def self.ransackable_attributes(auth_object = nil) column_names - column_names.select { |x| ["passw", "token", "encryp"].any? { |f| x.include?(f) } } + _ransackers.keys end def self.ransackable_associations(auth_object = nil) reflect_on_all_associations.map { |a| a.name.to_s } end # Last line of defence: never serialize secret-looking columns def as_json(options = {}) except = attributes.keys.select { |key| ["_ip", "sign_in", "_token", "password", "remember", "otp", "locked_at"].any? { |y| key.include?(y) } } super(options).except(*except) end end
| line | every model gets… |
|---|---|
include SoftDeletable | soft delete instead of real delete, and hidden deleted rows by default |
has_paper_trail | a versions history of every change (who and what), minus secret columns |
ransackable_* | safe search filters: a client can't filter by password_digest to guess it |
as_json | token / password / OTP columns removed from any default JSON |
ApplicationRecord (or a concern it includes), never by copy-pasting into each model. Model-specific behaviour stays in the model.The shape of one of our models
Every model is laid out in the same order, so you always know where to look:
# == Schema Information <- 1. generated by annotaterb, never hand-edit # id :uuid not null, primary key # name :text not null # app_key :text not null # ... class ClientApplication < ApplicationRecord has_many :roles # 2. associations has_many :permissions before_validation :generate_credentials, on: :create # 3. callbacks validates :name, :app_key, :api_secret, presence: true # 4. validations validates :app_key, uniqueness: true def notify_webhook(event_name, payload = {}) # 5. public behaviour return if webhook_url.blank? ClientApplicationWebhookJob.perform_later(id, event_name, payload) end def as_admin_json # 6. JSON shapes per audience { id:, allowed_hosts:, app_key:, name:, created_at:, updated_at:, webhook_url: } end def as_admin_show_json # the secret only on "show" as_admin_json.merge(api_secret:) end private # 7. private helpers + soft-delete hooks def generate_credentials self.app_key ||= loop do token = SecureRandom.hex(16) break token unless self.class.exists?(app_key: token) end self.api_secret ||= SecureRandom.hex(32) end def cascade_soft_delete roles.not_deleted.find_each(&:soft_delete!) end def cascade_restore nil # nothing to cascade end end
Associations
class User < ApplicationRecord has_many :user_roles has_many :roles, through: :user_roles # many-to-many via a join model end class UserRole < ApplicationRecord belongs_to :user # required by default: user must exist belongs_to :role end class Role < ApplicationRecord belongs_to :client_application has_many :user_roles has_many :users, through: :user_roles end
We use a real join model (UserRole) instead of has_and_belongs_to_many, because the link itself has data: a status, timestamps, soft delete and its own state machine.
Validations
validates :name, presence: true, uniqueness: { scope: :client_application_id }
validates :status, presence: true, inclusion: { in: %w[active inactive] }
validates :username, presence: true, uniqueness: {
case_sensitive: false,
conditions: -> { not_deleted }, # ignore soft-deleted rows
message: "is already in use by an active account",
}
validate :validate_permissions_inclusion # custom method
private
def validate_permissions_inclusion
return if permissions.blank?
return unless client_application
invalid = Array(permissions) - client_application.permissions.pluck(:name)
errors.add(:permissions, "contains invalid permissions: #{invalid.join(", ")}") if invalid.any?
endupdate_columns, insert_all and raw SQL skip them. Back important rules with database constraints (null: false, unique indexes, foreign keys).Scopes and soft delete
module SoftDeletable
extend ActiveSupport::Concern
included do
scope :not_deleted, -> { where(deleted_at: nil) }
scope :deleted, -> { where.not(deleted_at: nil) }
scope :with_deleted, -> { unscope(where: :deleted_at) }
default_scope { not_deleted } # every query hides deleted rows
define_model_callbacks :soft_delete, :restore # custom callbacks (r05)
end
def soft_delete! # sets deleted_at, cascades
def restore # clears it, re-checks uniqueness
def destroy # raises: use soft_delete! or hard_destroy!
def hard_destroy! # the only real DELETE
endEach model that includes SoftDeletable must implement cascade_soft_delete and cascade_restore. That forces you to decide, per model, what happens to children: User soft-deletes its user_roles; Department has nothing to cascade and says so with nil # nothing to cascade.
JSON shapes live in the model
def as_admin_json(with_client_application: false, with_permissions: true)
json = { id:, name:, created_at:, updated_at:, client_application_id:, description:, status:, deleted_at: }
json[:permissions] = permissions if with_permissions
json[:client_application] = client_application.as_admin_json if with_client_application
json
end
def as_client_json(with_client_application: false, with_permissions: true)
# same idea, for server-to-server clients
end- Explicit fields: new columns are private until you add them.
api_secretappears only inas_admin_show_json, never in a list. - One method per audience:
as_admin_json,as_client_json,as_admin_profile_json. with_*:flags for nested data, so a list endpoint doesn’t load associations it doesn’t show.{ id:, name: }is Ruby 3.1 shorthand for{ id: id, name: name }.
Class methods vs instance methods
# class method: no record yet; find, create or sync one def self.authenticate_and_sync!(username, password) entry = DirectoryService.authenticate!(username, password) # service does the I/O sync_from_directory!(entry) end def self.sync_from_directory!(entry) user = find_or_initialize_by(username: entry[:username].downcase) user.assign_attributes(email: entry[:email], display_name: entry[:display_name]) user.save! user end # instance method: acts on this record def toggle_admin! update(is_admin: !is_admin?) end
! means "raises on failure" (save!, sync_from_directory!) or "changes state" (toggle_admin!, soft_delete!). Methods ending in ? return booleans.State machines with AASM
class UserRole < ApplicationRecord
include AASM
aasm :status, timestamps: true, column: "status" do # timestamps: sets active_at / inactive_at
state :active, initial: true
state :inactive
event :activate do
transitions from: :inactive, to: :active
end
event :inactivate do
transitions from: :active, to: :inactive
end
end
def admin_actionables # tells the admin UI which buttons to show
rows = []
rows << "activate" if may_activate?
rows << "inactivate" if may_inactivate?
rows
end
endCheck yourself
You add a salary column to users. Which endpoints now expose it?
Our serializers list fields explicitly, so new columns stay private by default.
Why does Role.find(id) raise RecordNotFound for a soft-deleted role?
Use Role.with_deleted when you really need deleted rows (e.g. to restore).