Skip to content

Instantly share code, notes, and snippets.

@searls
Created November 4, 2022 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searls/b402ee729ceedb531f0f5f67093bb3ba to your computer and use it in GitHub Desktop.
Save searls/b402ee729ceedb531f0f5f67093bb3ba to your computer and use it in GitHub Desktop.
This is easily my least favorite Rails model validation scenario. An association exists and at least one associated item must conform to a specific condition for the owning side of the relationship to be considered valid. In this case, to avoid orphaning organizations
class Organization < ApplicationRecord
has_many :users
end
class User < ApplicationRecord
# Soft-deleteable with `discard!` https://github.com/jhawthorn/discard
include Discard::Model
belongs_to :agency
enum :role, {
manager: "manager",
owner: "owner"
}
validate :doesnt_relinquish_final_ownership
private
def doesnt_relinquish_final_ownership
# What would you do? Solution must:
#
# * Not allow `discard!` to be called on the final role=owner user of an organization
# * Not allow the final role=owner on an organization to be changed to role=manager
# * Cover both persisted and new_record? users on the organization.users association
# * Not result in an N+1 on organization.users
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment