Starter code and challenges for Validations & Error-Handling in Rails.
- Fork this repo, and clone it into your
develop
folder on your local machine. - Run
rake db:create db:migrate
in the Terminal to create and migrate your database. - Run
rails s
in the Terminal to start your server. - Navigate to
localhost:3000
in the browser.
-
Add validations to the
Pet
model. Pets are required to have bothname
andbreed
, andname
must be at least 3 characters. See the Active Record Validation docs for guidance. -
In the Terminal, open up the Rails console, and try adding an invalid pet to the database using the
.create
method:
irb(main):001:0> pet = Pet.create(name: "Ty")
What happens?
- Now try storing the invalid pet in memory with the
.new
method, and check if it's valid:
irb(main):001:0> pet = Pet.new(name: "Ty")
irb(main):002:0> pet.valid?
- Use
.errors.full_messages
to display the user-friendly error messages for the invalid pet you just created.
- The
pets#create
method currently looks like this:
#
# app/controllers/pets_controller.rb
#
def create
pet_params = params.require(:pet).permit(:name, :breed)
pet = Pet.create(pet_params)
redirect_to pet_path(pet)
end
What happens when you navigate to localhost:3000/pets/new
in the browser and try to submit a blank form?
Refactor your pets#create
controller method to better handle this error. Hint: Use .new
and .save
.
- Once you've refactored
pets#create
to redirect in the case of an error, add flash messages to show the user the specific validation error they triggered, so they won't make the same mistake twice. Hint: Set the flash message in the controller, and render the flash message in the layout (app/views/layouts/application.html.erb
).
-
You already have routes for
pets#edit
andpets#update
, since you're callingresources :pets
inroutes.rb
. Now set up controller methods forpets#edit
andpets#update
, as well as a view for editing pets (edit form). -
Make sure your
pets#update
method also handles errors by redirecting if the user submits invalid data and displaying a flash message in the view. -
Read the Rails docs for partials, and use a partial to DRY up the code in
new.html.erb
andedit.html.erb
.