Simple RESTful routes question

Hi, I’m new to the forum and new to rails. I’m working through the various tutorials, but I also have a real project for a client that I have to develop very quickly. So I have to learn quickly. Consequently I’m going to unabashedly post some relatively newbie questions here given the timeline on my project (insanely short!). Here’s an example…

routes.rb

resources :student, only: [:index, :new, :create]

student_controller, in the create action I have a line…

redirect_to student_index_url

I thought I should be using student_url instead, to hit the index action in the student controller, but the route doesn’t exist:

$ rake routes

  • student_index GET /student(.:format) student#index
  • POST /student(.:format) student#create
  • new_student GET /student/new(.:format) student#new

Can someone set me straight on this? I mean, what’s the RESTful approach I should take here? Thanks!

First of all your resources should be :students and not :student. Fix that and try again. Post an update after you’ve done that and we can see what else might be going wrong. Remember resources should always be plural, assuming you’re following the rules. good luck!

Once you’ve updated the resource to students as stated by @briandear , you’ll want to redirect to students_path. You shouldn’t need the _index in the path.

That totally worked. I didn’t realize I needed plural, and that without it I’d find myself in trouble. Thanks for the help!

Steps I took after @briandear message: destroy controller student, generate controller students, put the same new.html.erb and index.html.erb files in views/students, and in the students_controller used “redirect_to students_url” which worked.

For that last step though, sounds like I should be using students_path instead of students_url, maybe for convention? I can change it.

For routes within the app you typically use _path and then for links that will be displayed outside the app (email for example) you’d use the _url for links, images, etc.

1 Like

thanks! that clears up my confusion. I appreciate you guys keeping my rails straight.

Believe me this forum keeps me straighter than I help keep others! Good luck! It’s pretty exciting when things work after trying so hard to figure it out.