Nifty Rails Methods: link_to_if, link_to_unless
I have for some time been wanting to make a "definitive list of awesome rails methods". There are so many great built in methods that I didn't realize existed when I was trying to build something from scratch. Sometimes it's annoying to find out that thing you're trying to build already exists - but if you haven't put 500 hours into it, it's usually a relief.
So today the featured definitve list of awesome rails methods are link_to_if
and link_to_unless
.
The nice thing about this method is it's great for changing links based on if a user is logged in, if the page is current, etc. Instead of writing an if else statement you can DRY it up by using link_to_if
or link_to_unless
. I found it fun to play around with and very useful as well. I personally used it for a complicated if else to mark a category for a prodcut as current. There is also an link_to_unless_current
which I didn't end up using because it wouldn't mark both the current category and parent category as active, link_to_if
worked much better for that.
Below is an example from the Rails API
More about these methods can be found on the Rails API.