When creating a link with link_to with an instance variable as an argument, a link that I do not remember specifying was generated. What was generated was a link to that page, which apparently happens when you pass nil as an argument. I couldn't find the related page, so I will describe the verification result and the solution. Since we are a beginner, we would appreciate it if you could comment if it is misplaced.
ruby 2.6.5 Ruby On Rails 6.0.0
TL;DR
http://localhost:3000/hoge/When the following description is made in the page 3
A link for that page will be generated as shown below.(Who will use it)
<%= link_to nil,nil %>
=> <a href="/hoge/3">/hoge/3</a>
If there is a possibility that nil will be included in the passed data, if you do the following, it will be blank in the case of nil.
@hoge ・ ・ ・ url data or nil
<%= link_to_if @hoge, @hoge, @hoge %>
If there is a possibility of entering an empty string or space (should that be validated?)
<%= link_to_unless @hoge.blank?, @hoge, @hoge %>
link_to (how to use)
link_to(Link text,path[,option,HTML attribute or event attribute])
If the link text is nil, the content entered in the path will be displayed as the link text.
<%= link_to nil, "https://twitter.com/" %>
=> <a href="https://twitter.com/">https://twitter.com/</a>
If the path is nil (http)://localhost:3000/hoge/(Listed on the page)
A link for the current page is generated
<%= link_to "hoge", nil %>
=> <a href="/hoge/">hoge</a>
So the link text is also nil,If the path also contains nil,
Since the path is nil, the link of the current page is generated
→ Since the link text is nil, it seems that the link of the current page is displayed.
How to solve
How to use
link_to_if(Conditional expression,Link text, url [,option,HTML attribute or event attribute])
@hoge ・ ・ ・ url data or nil
<%= link_to_if @hoge, @hoge, @hoge %>
If you do like ↑@If hoge is nil, nothing is generated, only when there is data.
https://railsdoc.com/page/link_to https://railsdoc.com/page/link_to_if The movement when nil is inserted is written in ↓. (Because link_to eventually calls url_for) https://github.com/rails/rails/blob/f33d52c95217212cbacc8d5e44b5a8e3cdc6f5b3/actionview/lib/action_view/routing_url_for.rb#L79
Recommended Posts