Search code examples
ruby-on-railsruby-on-rails-5.1

Getting "Uninitialized constant" routing error when loading a view


I'm a beginner to both ruby and rails, and using Rails 5.17 to develop a web app for a class.

Creating the empty Rails project was successful, but something is going wrong when creating a new controller. I generated a new controller named cars from the root of the project, which was successful. There was a file in app/controllers named cars_controller.rb which looks like this:

 class CarsController < ApplicationController
 end

I added a method to this file named hello that does nothing.

I then created a file named cars.html.erb in the app/views/layouts directory. This file is a basic page of html code.

In config/routes.rb, I added the following:

 get '/cars', to:: 'cars_controller#hello'
 resources: cars

After all of this, I ran rails server, and opened localhost:3000 in a browser. This brings up the normal Ruby on Rails welcome page.

But when I go to localhost:3000/cars, I get the following:

Routing Error uninitialized constant CarsControllerController

I've tried changing the name of the cars_controller.rb file. I've tried changing the name of the class in the controller file from CarsController to Cars. I've tried many different routes in routes.rb. I finally tried uninstalling Rails 5.17 and installing Rails 5.13.

I'm very confused, and I'd be grateful for any advice I can get. Thanks in advance!


Solution

  • One of the great things about Rails is its preference for convention over configuration. However, for this to really benefit you, you need to stick to doing things “The Rails Way” rather than your own way, wherever possible.

    In this case, start by getting rid of your custom get route, and just use resources :cars.

    From the command line, run rake routes (you might be able to run rails routes on your rails version too) and see the routes that it has created for you.

    Now, rename the method you added to your CarsController from hello to index.

    Move your hello.html.erb file from app/views/layout to app/views/cars/index.html.erb.

    Finally, start the rails server (rails start) and load the url http://localhost:3000/cars in your browser.

    —-

    Note that templates in app/views/layout have a special purpose. These are used to apply a general template to your views. Look up the use of layout within a controller for more details