« Highly useful assert_select | Main | Finished Rails Book »

Using Rails link_to_if

There are a lot of great helper methods in rails, and I need to remember to use more of them, one I over looked for a long time that I have found useful is link_to_if

<%= link_to_if logged_in?, "#{item.name}", :controller => 'items', :action => 'show', :id => item %>

replaces the much longer and more verbose:

<%- if logged_in? %>
<%= link_to , "#{item.name}", :controller => 'items', :action => 'show', :id => item %>
<%- else %>
<%= item.name %>
<%- end %>

I like being able to replace five confusing lines with one single simple solution. The link_to_if helper writes a link if the condition is met, otherwise it just outputs the text that would have been in the link. Very cool.

Also if you want to use Ajax forms with multiple submit buttons in Rails, here is the solution.

Lastly if you are trying to write a selector and want to make sure the test is returning the html you expect you can add puts @response.body into the test after the page call and see the response. This has been useful to me a few times.

Comments (2)

Dom^2:

you just hurt my head

shawn:

I think you need to get outside. Listen to music, look at some breasts, have a beer, throw a ball, something. Step away from your computer.

Post a comment


Type the characters you see in the picture above.

Web 2.0 craziness

View Dan Mayer's profile on LinkedIn


I Power Seekler
I Power Seekler

www.flickr.com
This is a Flickr badge showing public photos and videos from mayer_dan. Make your own badge here.

Creative Commons License
This weblog is licensed under a Creative Commons License.