Clean way in Rails to conditionally change the link_to location

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 %>

Answers


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>

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


Need Your Help

Disable click in DataGridvIew

vb.net visual-studio-2010 visual-studio datagridview

I have a DataGridView 'DGV' that is set to readonly via the properties panel. My question is, why if the DGV is set to readonly, users are able to click within the grid? I thought that by setting a...

android how to use calender with countdown timer in adapter class?

android listview calendar adapter countdowntimer

i have a listview in which countdowntimer is working.,now i want to add use countdowntimer with calender.,in which time of calender should be countdown like reverse order..,i tried some code but th...