Last active
October 11, 2023 19:38
-
-
Save eric1234/136aa1552186912f337c8e652ba69c76 to your computer and use it in GitHub Desktop.
composed model example
This file contains 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
concern :ComposedModel do | |
include ActiveModel::Model | |
def valid? | |
objects.all?(&:valid?) && super | |
end | |
def save! | |
raise ActiveRecord::RecordInvalid, self unless valid? | |
transaction { objects.each &:save! } | |
end | |
private | |
delegate :transaction, to: ApplicationRecord, private: true | |
def merge_errors_for! object, from:, to: | |
object.errors.where(from).each { errors.import _1, attribute: to } | |
end | |
end |
This file contains 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 Space::Registration | |
include ComposedModel | |
attr_accessor *%i[space_name owner_name email] | |
def valid? | |
super | |
ensure | |
merge_errors! | |
end | |
private | |
def objects = [space, owner, auth] | |
def merge_errors! | |
merge_errors_for! space, from: :name, to: :space_name | |
merge_errors_for! owner, from: :name, to: :owner_name | |
merge_errors_for! auth, from: :identifier, to: :email | |
end | |
memoize def space = .... | |
memoize def owner = .... | |
memoize def auth = ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment