当前位置: 动力学知识库 > 问答 > 编程问答 >

How to show specific link to user that's signed in and on specific page in rails?

问题描述:

I have the following code for part of my navigation:

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

I want different links to show depending on where the "user_signed_in" is. However, my <% elsif user_signed_in? and params[:controller] == 'profiles#edit' %> doesn't seem to be working.

What am I doing wrong?

网友答案:

profiles is your controller, and edit is your action, so you need to specify them as separate things:

elsif user_signed_in? && params[:controller] == 'profiles' && params[:action] == 'edit'
网友答案:

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.

网友答案:

You can use params[:controller], but it only contains the name of the controller. params[:action] will contain the action-name.

Even cleaner is to use controller_name and action_name which are also available.

Like so:

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

网友答案:

If you want to determine the "url" for showing links or hiding it , you can use :

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

or the url you'd like . As you can guess , the path's format accepts wildcards too : /profiles/*

分享给朋友:
您可能感兴趣的文章:
随机阅读: