开发者

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 cleane开发者_开发知识库r way

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜