Created
October 6, 2012 19:16
-
-
Save florida/3845836 to your computer and use it in GitHub Desktop.
Getting an error from saving an entry
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
# 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