Use named route in notes#index
This commit refactors both our Request Routing and View layer’s code to
share helper method.
The "/notes/new"
String was duplicated in both the notes#index
template and our application’s route declaration file.
A String value duplicated in this way across disparate files can be
considered a “magic string” , since it’s equivalence in
two seemingly unrelated areas of the codebase is both important and
unclear.
By declaring the get "/notes/new"
route declaration with the as:
"new_notes"
option , Rails will generate new_notes_path
and new_notes_url
routing helpers which are made available
within the view layer.
Routing helpers are a discrete list of methods, so attempting to invoke
a route helper that does not exist will raise a NoMethodError
when
invoked.
When we run the test suite, it passes.
Collapse app/views/notes/index.html.erb
Expand app/views/notes/index.html.erb
app/views/notes/index.html.erb
diff --git a/app/views/notes/index.html.erb b/app/views/notes/index.html.erb
index 69d5ed8..3be9028 100644
--- a/app/views/notes/index.html.erb
+++ b/app/views/notes/index.html.erb
@@ -1,3 +1,3 @@
-<a href="/notes/new">
+<a href="<%= new_note_path %>">
Share a Note
</a>
Collapse config/routes.rb
Expand config/routes.rb
config/routes.rb
diff --git a/config/routes.rb b/config/routes.rb
index 1d005be..0b48db8 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,6 +1,6 @@
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
- get "/notes/new", controller: "notes", action: "new"
+ get "/notes/new", controller: "notes", action: "new", as: "new_note"
post "/notes", controller: "notes", action: "create"
get "/", controller: "notes", action: "index"