link_to_if
is a great way to conditionally render a link, but it can be a trap if you're not careful.
by John Norris
link_to_if
will either output the string as a link if the criteria is met, or will output just the string.
e.g.
<%= link_to_if policy(@model).edit?, "Edit", edit_model_path(@model) %>
Everyone sees “Edit”, and some people can click it. Not ideal.
If we want to only output a link if you can edit and nothing at all if you can’t, we need to not use link_to_if
at all:
<%= link_to "Edit", edit_model_path(@model) if policy(@model).edit? %>
A good use case for link_to_if
is if the value standsalone on its own but can also sometimes be a link. E.g. Where we output the name of the lead but you can also click through to it if you’re allowed:
<%= link_to_if policy(@lead).show?, lead.name, lead_path(@lead) %>
Everyone sees the name, and some people can click it. Perfect.