Skip to content

Run Model Validations

Janko Marohnić edited this page Dec 6, 2023 · 1 revision

If you already have model validations defined when the account is created, and you would like to reuse them, you can run them in the before_create_account hook:

before_create_account do
  # ...
  if rails_account.invalid?
    rails_account.errors.to_hash.each do |name, errors|
      throw_error_status(422, name.to_s, errors.first)
    end
  end
end

Make sure to call #rails_account only after you've assigned necessary column values to the account hash. You can always assign additional attributes to the model instance before running validations.

If you want to run model validations in context where there is no handling of validation errors (e.g. rodauth-omniauth), you could set an error flash and redirect instead:

before_omniauth_create_account do
  # ...
  if rails_account.invalid?
    validation_error = rails_account.errors.full_messages.first
    set_redirect_error_flash validation_error
    redirect omniauth_login_failure_redirect
  end
end
Clone this wiki locally