23 May
Infer name with link_to - Rails Tricks Issue 8
Hi, this week I want to tell you about an improvement coming in Rails 7.1. When you are using the link_to helper, it can infer the URL from the object you are passing to it as the second parameter:
Olivier Lacan, in Rails 7.1 that will be possible. You can specify what the text should be in the to_s method of the object, and you will only need to pass the object to the helper:
I love these small improvements to the framework.
Wouldn’t it be nice to infer the content of the a tag too? Thanks to While we are talking about link_to, I’d like to mention something about this helper. The second parameter accepts a string for the href attribute of the a tag. The HTML specification permits various protocols for that attribute, including javascript, so for instance, you can make a dummy link with the following:
Now let’s say in your application a user can specify the URL for their blog and you pass that to link_to:
That’s it for today. You may want to check out a post I wrote about a related topic about using link_to_if and link_to_unless to conditionally render a link in Rails.