Today we talked about
- the
routes.rb
file in Rails - the purpose of a controller in Rails
- how to use
resources :things
to create eight RESTful routes
Reading
Create a new rails project:
$ rails new routes-controllers-practice
$ cd routes-controllers-practice
$ bundle
- Add this route in your
routes.rb
file:
Rails.application.routes.draw do
get '/students', to: 'students#index'
end
Add a controller and a method within that controller that renders the text: "You've hit the students index page."
- Modify your routes file:
Rails.application.routes.draw do
get '/students', to: 'students#index'
resources :courses
end
Add a controller and all methods that the controller will need in order to use the routes generated by this. Don't worry about rendering text. Just make sure you have (empty) methods defined.
- Modify your routes file:
Rails.application.routes.draw do
get '/students', to: 'students#index'
resources :courses
resources :teachers
end
Can you add something to the end of the resources :teachers
line in order to only create the show
and index
routes instead of all eight routes generated by resources
? Add a controller for teachers
and ensure that your show
and index
actions work.
- Add a root path so that we can navigate to
http://localhost:3000/
. Have this route go to theindex
action in a welcome controller. Create the controller and action, and test out the root by starting your server and navigating to'/'
.
Extensions:
-
With
resources :teachers
you typically access a single teacher with a numeric ID like/teachers/6
. Can you make it so their last name is used instead of the numeric ID (like/teachers/warbelow
) and I can accessparams[:last_name]
? Use this blog post and/or this Stack Overflow answer. These blog posts go into depth on overwriting a method (to_param
) in your model, but since we don't have a model, you don't need to worry about that part. -
What does the following piece of code do? How do you have to modify your controllers in order to access these routes?
Rails.application.routes.draw do
namespace :school do
resources :teachers
end
end