Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Rails Designer
Rails Designer

Posted on • Originally published atrailsdesigner.com

     

Rails link_to_if and link_to_unless

This article was originally published onRails Designer


Rails is packed with nifty, small helpers that help you not reinvent the wheel. Every once in a while you remember one that you are sure some of you are not known with.

Today and I want to quickly go over:link_to_if andlink_to_unless.

They both act the same as the, probably, knownlink_to helper, but, as you guessed, allow a conditional.

Basics

The syntax forlink_to_if looks like this:

link_to_if(condition,name,options={},html_options={},&block)
Enter fullscreen modeExit fullscreen mode

Or with actual values:

<%=link_to_if(Current.user.present?,"Profile",profile_path)%>
Enter fullscreen modeExit fullscreen mode

This will, ifCurrent.user.present? returns true, render a typicallink_to, but if it returnsfalse it will return just the textProfile.

link_to_unless accepts the same attributes, but does the opposite. Take this example:

<%=link_to_unless(current_page?(home_path),"Home",home_path)%>
Enter fullscreen modeExit fullscreen mode

This will render a typicallink_to unlesscurrent_page?(home_path) returns true. You can imagine this is useful innavigations.

Tweak the conditional render

You can also tweak what (if anything) is rendered when the conditional is (not) met. Like so:

<%=link_to_if(Current.user.has_role?(:admin),"Manage Users",admin_users_path)do%><div><p>You need to be an admin to manage users.</p><p>If you believe this is an error, please contact support.</p></div><%end%>
Enter fullscreen modeExit fullscreen mode

I have used this to show links to features a certain account/user didn't have access to, but then show a modal for an upsell. Works great.

<%=link_to_if(Feature.enabled?(:ai_access),"Add AI Magic",setting_ai_path)do%><%=link_to"Add AI Magic",upsell_path(highlight:"ai"),data:{turbo_frame:"modal"}%><%end%>
Enter fullscreen modeExit fullscreen mode

And that's it. Yet another small, but useful little helper in Rails.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I help teams around the world make their Rails apps a bit nicer to maintain and look at. 🎨 Also kickstart SaaS' in a month. 👷 And built a Rails UI Components library, used by 1000+ developers. 🚀
  • Location
    Amsterdam, The Netherlands
  • Joined

More fromRails Designer

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp