Wednesday, August 3, 2011

Passing a path into a partial

I recently figured this out, and I thought others might find this helpful, too.

Ever want to pass a path into a partial - say, for a header, where there's always going to be a link in this one spot, but the actual path of that link changes? I encountered this problem when developing a mobile web app, where in the top left header section, I always wanted a "back" link, but the actual path of this link varied depending on the page.

Here's how I did it:
In the partial:
<% unless path.nil? %>
 <%= link_to "Dining Hall", send(path) %>
<% end %>
In the view that renders the partial:
<%= render :partial => "layouts/partials/header", :locals => { :path => "root_path" } %>

Instead of root_path, you could put, for example, books_path. Note, however, that passing "@book" or @book does not work, so this still has its limitations.

The whole trick is using the "send" method in the link_to. http://apidock.com/rails/ActiveRecord/Associations/AssociationProxy/send

I certainly found this trick to be useful, and perhaps you will too.

No comments:

Post a Comment

Please be considerate in what you say.