Skip to content

Latest commit

 

History

History
71 lines (49 loc) · 2.47 KB

routes_controllers_rails.markdown

File metadata and controls

71 lines (49 loc) · 2.47 KB

Routes and Controllers in Rails

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

Your Task

Reading

Create a new rails project:

$ rails new routes-controllers-practice
$ cd routes-controllers-practice
$ bundle
  1. 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."

  1. 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.

  1. 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.

  1. Add a root path so that we can navigate to http://localhost:3000/. Have this route go to the index action in a welcome controller. Create the controller and action, and test out the root by starting your server and navigating to '/'.

Extensions:

  1. 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 access params[: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.

  2. 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