link_to_if
is a great way to conditionally render a link, but it can be a trap if you're not careful.
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.
— John Norris
Who are Dragon Drop?
Dragon Drop is a specialist web and app development agency. The team has extensive full-stack technical credentials and a strong focus on user experience.
The Dragon Drop founding team have over 40 years of web development and project experience. They have managed or developed over 100 significant ecommerce and web projects during their careers, including implementations for major UK high street retailers, financial services companies and government agencies.
Their approach to innovative solutions stems from perspectives gained as retailer, software supplier and web agency.