Skip to content

Instantly share code, notes, and snippets.

@searls
Created January 7, 2020 03:42
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/e5463ceb29290e2d4bdd9f07170c0c62 to your computer and use it in GitHub Desktop.
Save searls/e5463ceb29290e2d4bdd9f07170c0c62 to your computer and use it in GitHub Desktop.
class SaveRevalidly
Result = Struct.new(:saved, :errors, keyword_init: true)
def call(model)
if model.save
Result.new(saved: true, errors: model.errors.messages)
else
original_errors = model.errors.messages.dup
if model.invalid? && model.errors.keys.present?
model.restore_attributes(model.errors.keys)
subsequently_succeeded = model.save
Result.new(
saved: subsequently_succeeded,
errors: original_errors.merge(model.errors.messages)
)
else
Result.new(saved: false, errors: original_errors)
end
end
end
end
@raul
Copy link

raul commented Jan 8, 2020

Leaving this for context :)

Is there a standard pattern in Rails to unset/reset a model's attributes to previous values or defaults when the user provides something invalid? (In this case I don't want to issue a validation error and ask the user to fix it, I just want to reset to a sensible default)

https://twitter.com/searls/status/1214369338154635265

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment