Today I Learned

hashrocket A Hashrocket project

Conditional link_to

In your Rails view, you can conditionally render links thanks to ActionView::Helper using #link_to_if

<%= link_to_if(current_user.nil?, "Login", login_path) %>

When this condition is true it would output:

<a href="/sessions/new/">Login</a>

When it is false it just outputs the text:

Login

If you want a custom rendering for false values, just pass that into a block:

<%= link_to_if(current_user.nil?, "Login", login_path) do
  link_to("Logout", logout_path)
end %>

NOTE: There is also an inverse link_to_unless method available

Here's the docs if you're interested.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.