Comments on Cannot find definition of function that returns a path
Parent
Cannot find definition of function that returns a path Question
I want to find the place in the codebase where a path is defined, but searching for the function that creates it gives no results apart from the usage of that function.
For example, see thread.html.erb
, line 142:
<%= link_to 'See the whole thread', comment_thread_path(@comment_thread) %>.
This calls a function comment_thread_path
but searching for this function finds no definition of it.
Post
The function comment_thread_path
is created automatically by Rails, based on the information provided in config/routes.rb
.
See Rails Routing from the Outside In for further details.
Specifically, line 236 of config/routes.rb
says (enclosing scope included for context):
scope 'comments' do
...
get 'thread/:id', to: 'comments#thread', as: :comment_thread
...
end
This responds to a GET request on the route /comments/thread/:id
by:
- First calling the
thread
method of theCommentsController
- Then rendering the
app/views/comments/thread.html.erb
view.
See Action Controller Overview for further details.
The comments#thread
in the routes file determines both:
- Which controller and method to call (being in the format
controller#method
) - Which view to render and where to find it (being in the format
directory#viewfile
)
The optional as: comment_thread
overrides the default name that Rails would otherwise use in its automatically generated helper functions (otherwise it would use the default comments_thread
- note the pluralisation). Now comment_thread_path
and comment_thread_url
are available, each a function taking a thread id as argument:
- Calling
comment_thread_path(123)
returns/comments/thread/123
- Calling
comment_thread_url(123)
returns the same thing but including the domain at the beginning, such asexample.com/comments/thread/123
.
0 comment threads