Last active
January 31, 2018 22:51
-
-
Save m1foley/1b074265432939ac8b960c8488d7edab to your computer and use it in GitHub Desktop.
Form object with error handling
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 Signup | |
include ActiveModel::Model | |
attr_accessor :email, :team_name | |
validates :email, presence: true | |
validates :team_name, presence: true | |
def save | |
return false unless valid? | |
user = User.new(email: email) | |
team = Team.new(user: user, name: team_name) | |
if user.save && team.save | |
true | |
else | |
add_errors_from(user, team) | |
false | |
end | |
end | |
end | |
# ActiveModel convenience monkeypatch | |
module ActiveModel::Validations::HelperMethods | |
def add_errors_from(*objects) | |
objects.compact.each do |object| | |
object.errors.each do |name, message| | |
self.errors.add(name, message) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment