For example, suppose you have the following blogs/edit.html.erb
as a Rails View file:
<h1>Editing Blog</h1>
<%= render 'form', blog: @blog %>
<%= link_to 'Show', blog_path(@blog) %> |
<%= link_to 'Back', blogs_path %>
The 5th line blog_path (@blog)
is a helper method that generates a path like / blogs/10
. (Here, it is assumed that the value of @ blog.id
is 10.)
As you can see, you would normally pass an instance of ActiveRecord like @ blog
as an argument to blog_path
.
However, calling blog_path
without arguments as follows does not cause an error.
<%= link_to 'Show', blog_path %> |
The generated path will be / blogs/10
as before.
The same is true not only in View but also in the controller.
def update
if @blog.update(blog_params)
# blog_path(@blog)Without writing/blogs/Redirected to 10
redirect_to blog_path, notice: '...'
else
render :edit
end
end
Why?
I think that the above edit screen is usually called with the following path (URL).
/blogs/10/edit
If you call a helper method with no arguments like blog_path
,/blogs/10
will be generated by inheriting the id (10 in this case) included in the path at the time of request.
If you write app.blog_path
in rails console etc., an error will occur because there is no id to inherit.
> app.blog_path
Traceback (most recent call last):
1: from (irb):2
ActionController::UrlGenerationError (No route matches {:action=>"show", :controller=>"blogs"}, missing required keys: [:id])
Did you mean? blog_url
blogs_url
blogs_path
new_blog_url
blog_path
with no arguments?Personally, I don't think so.
This is because it is safer to write blog_path (@blog)
to explicitly indicate that "the path you want to generate with this method is this id (this object)" rather than implicitly determining the id. ..
Also, if there is a habit of omitting arguments, a path may be generated with an unintended id depending on the logic of View, which may cause unexpected problems.
There was such a description in the documentation of the url_for
method.
https://edgeapi.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for
Missing routes keys may be filled in from the current request's parameters (e.g.
:controller
,:action
,:id
and any other parameters that are placed in the path).(Author's translation) The missing routing key is obtained from the request parameters (eg
: controller
,: action
,: id
, and other parameters contained in the path).
As stated in the above documentation, writing url_for (controller:'blogs', action:'show')
instead of blog_path
will generate/blogs/10
as well. I will. (More specifically, just url_for (action:'show')
is OK)