Skip to content

Instantly share code, notes, and snippets.

@florida
Created October 6, 2012 19:16
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 florida/3845836 to your computer and use it in GitHub Desktop.
Save florida/3845836 to your computer and use it in GitHub Desktop.
Getting an error from saving an entry
# Validations may cause errors
# since if an object is required to have certain values
# and saved without them it will not be saved to the database.
# Here I am creating a method that will accept an object and attempt to save it
# it will also display the relevant errors
def check_for_errors(obj)
if (obj.save)
puts "save was successful"
else
puts "Save failed"
obj.errors.messages.each { |e| puts e }
end
end
# Let's say this is a completely valid entry, and it will save properly
new_entry = Object.new(:name => "I'm an object" :description => "I will go to the database")
# Now we pass the object to the method to save and check for errors
check_for_errors(new_entry)
# The expected output will be
##########################################
# save was successful
# Now i'm just going to create an object with just a name
# and lets assume that it needs both name and description
invalid_entry = Object.new(:name => "I am an invalid object")
# Now we passed the invalid entry to the method
check_for_errors(invalid_entry)
# The expected output will be
##########################################
# save failed
# description
# can't be blank
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment