0

我的部分导航有以下代码:

  <% if user_signed_in? %>
    <li><%= link_to 'Edit Profile', edit_profile_path(current_user.profile) %></li>
    <li><%= link_to 'Edit Account', edit_user_registration_path %></li>
  <% elsif user_signed_in? and params[:controller] == 'profiles#edit' %>
    <li><%= link_to 'View Profile', profile_path(current_user.profile) %></li>
    <li><%= link_to 'Edit Account', edit_user_registration_path %></li>
  <% else %>
    <li><%= link_to 'Sign up', new_user_registration_path %></li>
  <% end %>

我希望根据“user_signed_in”的位置显示不同的链接。但是,我的<% elsif user_signed_in? and params[:controller] == 'profiles#edit' %>似乎没有工作。

我究竟做错了什么?

4

4 回答 4

2

Besides what others already mentioned, as this code is written, when user_signed_in? is true you will always fall into the first block and never hit elsif block. You would have to fix condition that deals with controller and action AND make this a first condition so that your code will execute as intended.

于 2012-11-19T02:21:02.223 回答
1

profiles是您的控制器,edit是您的操作,因此您需要将它们指定为单独的事物:

elsif user_signed_in? && params[:controller] == 'profiles' && params[:action] == 'edit'
于 2012-11-18T16:52:26.563 回答
1

您可以使用params[:controller],但它只包含控制器的名称。params[:action]将包含动作名称。

更清洁的是使用controller_nameaction_name也可以使用。

像这样:

<% elsif user_signed_in? and controller_name == 'profiles' and action_name == 'edit' %>

Tip for the future

You pose this question, but in fact it is extremely easy to show what params[:controller] contains, just do something like

 <%= "Controller name = #{params[:controller]}" %>

somewhere in your view. Temporary of course :) But then you would immediately know why your condition does not work.

HTH.

于 2012-11-19T00:11:11.510 回答
0

如果您想确定显示或隐藏链接的“url”,您可以使用:

 if request.path == "/profiles/edit" 

或您想要的网址。你可以猜到,路径的格式也接受通配符:/profiles/*

于 2012-11-18T16:56:58.103 回答