I'm running into a problem with a Rails 7 app. I have the following routes defined:
Rails.application.routes.draw do
# Defines the root path route ("/")
root "site#index"
# Routes for rest of site
get "/site", to: "site#index"
resources :projects
resources :coursework
The controllers of my models Projects and Courses are both the default as generated by rails generate controller
(i.e. they both have no actions), and they both have no views in their app/views/
folders. However, this index.html.erb
for my site
will produce an error:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Minimum Reproducible Example</title>
</head>
<p>
<%= link_to "View All Courses", :coursework %>
<%= link_to "View All Projects", :projects %>
</p>
ActionController::UrlGenerationError in Site#index
No route matches {:action=>"show", :controller=>"coursework"}, missing required keys: [:id] Did you mean? coursework_url
rails routes
shows both projects#show
and coursework#show
.
If I comment out the first link, it will work perfectly (the page will render and View All Projects will error upon being clicked on as expected, as I have not defined an index
in controller or view). Why would this differ for the two controllers which are identical except in name?
Any help is appreciated. Thanks!
CodePudding user response:
In link_to "View All Projects", :projects
, because projects is plural, rails is generating a link to the index route, /projects
, which works fine.
But with link_to "View All Courses", :coursework
, since coursework is singular, it is trying to route to the show route, /coursework/:id
, and failing because an id wasn't provided.
Rails suggests pluralizing your controllers to allow many of these routing niceties to work (Guide link), so I'd suggest renaming the controller to something like CourseworksController
or CoursesController
.