Retro-reading RailsSpace, part 2: link_to and Friends

This is Part 2 in my series Retro-reading RailsSpace. Despite the book being slightly out of date, and geared toward beginners, it’s a classic. I’m reading it (finally) and posting what I learn.

link_to has friends: link_to_if, link_to_unless, and link_to_unless_current

link_to has useful variations:

  • link_to_if: only make the name linked if the first param equates to true.
  • link_to_unless: only make the name linked if the first param equates to false.
  • link_to_unless_current: don’t create the link if it leads to the page you’re already on.

The first two take an extra parameter, prepended to the parameter list. That parameter is a conditional that needs to equate to true or false. link_to_unless_current doesn’t need an extra parameter, because it already knows what to look for. Here are some examples:

# user types: member, moderator, admin #

# generate a link only if the user is admin #
link_to_if current_user.admin?, 'admin', admin_path

# generate a link only if the user is NOT admin #
link_to_unless current_user.admin?, 'request admin status', request_admin_path

# generate this link only if we're not already on this page #
link_to_unless_current 'help', help_path

By default, all of these will display the same text you would have seen in the link, just not linked, if their conditions aren’t met. But that wouldn’t work too well for the admin/non-admin links, because we’d really rather hide them altogether. You can do this by passing in a block. With a block, you can respond to unmet conditions however you’d like. If the condition is NOT met, the link is not created, and the block is executed instead. The fun part is, that block can contain a link itself!

# generate an admin link, or request link, whichever is needed #
link_to_if current_user.admin?, 'admin', admin_path do
  link_to 'request admin status', request_admin_path

This might be handy, and I didn’t know it existed before RailsSpace.


Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: