Created
November 4, 2022 12:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Organization < ApplicationRecord | |
has_many :users | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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