Rails link_to, link_to_if and link_to_unless


1. link_to
This is basic syntax to link other urls and actions.whivh creates a link tag of the given name using a URL created by the set of options.

link_to ‘Alter Challenge’, edit_challenge_path(@challenge)

2. link_to_if
This link_to helper create a link tag of the given name using URL only under certain circumstances,otherwise only the name is returned.

link_to_if user_logged_in?, “Create Challenge!”, new_challenge_path

Sometimes, it become irritating when user trying to do create challenge but link not working for him without having a clue how to.
Fortunately Action View provides a solution:

link_to_if user_logged_in?, “Create Challenge!”, new_challenge_path do
link_to “Log in to create challenge”, new_user_session_path
end

The block is executed in case the condition is not met. So if user aren’t logged in, We give them a hint how to create challenge.

2. link_to_unless
The counterpart to link_to_if is link_to_unless. You can use the simple version that will either render a link or just text.

link_to_unless user_signed_in?, “Login”, new_user_session_path

advanced version using a block:

link_to_unless user_signed_in?, “Login”, new_user_session_path do
link_to “Create Challenge!”, new_challenge_path
end