Link_to_if - text still present

217 Views Asked by At

I want to do a conditional link_to which is displayed only if the user is logged in as an admin. So I did this :

Application Controller

def confirm_admin
 if session[:role] == "admin"
   @isAdmin = true
 else
   flash[:notice] = "Vous n'avez pas les droits pour accéder à cette page."
   redirect_to root_path
   return false
 end
end

View

<%= link_to_if is_admin, 'Editer l\'idée', edit_idee_path(@idee), :class => "editer custom-button" %>

The link disappeared but the text is still present, do you have any idea why ?

2

There are 2 best solutions below

1
On BEST ANSWER

link_to_if only makes the text no-link text; it removes the link from the text, not the text itself.

What you are trying to do, you can achieve it through following code:

<% if is_admin %>
  <%= link_to 'Editer l\'idée', edit_idee_path(@idee), :class => "editer custom-button" %>
<% end %>
<%# Now, it will remove both: link as well as text. %>
0
On

A better way to do this is to add an empty block at the end of the link_to_if statement, this will display the text when conditional is true and not display it when the conditional is false.

E.g.

flash[:notice]= "Some text that will always show. 
#{view_context.link_to_if(user.exists?,
'A hyperlink that will show based on conditional', 
user_path)**{}**}"