3

SO i have this link_to

 <li><%= link_to "Home", root_path %></li>

but if its an admin i want go to a different location like below...I know i can do this but is there a cleaner way

 <% if admin_user %>
 <li><%= link_to "Home", admin_path(current_user) %></li>
 <% else %>
 <li><%= link_to "Home", root_path %></li>
 <% end %>
Phrogz
  • 296,393
  • 112
  • 651
  • 745
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321

2 Answers2

3

A little cleaner

<li><%= link_to "Home", admin_user ? admin_path(current_user) : root_path %></li>

or where ever you computed admin_user, presumably in the controller, create an additional variable containing the appropriate path and use it in the view instead. e.g.

# in controller
home_path = admin_user ? admin_path(current_user) : root_path

# in view
<li><%= link_to "Home", home_path %></li>
Steve Wilhelm
  • 6,200
  • 2
  • 32
  • 36
2

A more flexible way, e.g. if you want to change the name of the link also:

<li><%= 
  link_to_if admin_user, "Home", admin_path(current_user) do
    link_to "Home", root_path
  end
%></li>

http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_if

konyak
  • 10,818
  • 4
  • 59
  • 65