简体   繁体   中英

Disable link_to tag in Rails3+

I used the following code:

<%= link_to image_tag("edit.png", :alt => "Edit"), edit_user_path(user) %>

I want to disable this link and image, so I added :disabled=>true to the code, but it's not disabling. Why not, and how do I disable them?

I'm not sure what @lamrin wanted with this question, but I suppose that it is something like this:

<%= link_to_if condition?, image_tag("edit.png", :alt => "Edit"), edit_user_path(user) %>

With this code above, the image would have a link if the condition? is true

In my case this code below worked (a more complicated example):

link_to_unless disabled, (content_tag :div, "", :class => "vote " + vote_class, :title => title), resource_user_path({ :id => resuser.id, :resource_user => {:id => resuser.id, :resource_id => resource_id, :user_id => current_user_id, :vote => vote_value}}), :remote => true, :method => http_method  

This link may also help with this approach:

http://railskey.wordpress.com/2012/07/19/rails-link_to-link_to_if-and-link_to_unless/

Unlike buttons, hyperlinks cannot be "disabled". You can do the following though, assuming you have jQuery included on your pages:

<%=link_to image_tag("edit.png", :alt=>"Edit"), edit_user_path(user), :id => "mylink" %>

Add the following Javascript to your page:

$('#mylink').click(function(e){
  e.preventDefault();
});

In answer to your question, there is no :disabled option for the link_to helper in Rails, and it is not a valid attribute for a elements either. I believe the reason people tend to get confused with this in Rails is that ":disabled => true" does work IF you are using Bootstrap. So to fix this issue you can either follow Gupta's approach, or just add Bootstrap (which will give you some default CSS as well, so people don't get frustrated trying to click the link)!

Re: link_to method in rails: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to )

Re: the "disabled" attribute on a elements: Is 'disabled' a valid attribute for an anchor tag

Re: Bootstrap "disabled" class or attribute with bootstrap: http://getbootstrap.com/css/#anchor-element-1

1)One solution is to render just image_tag when you do not want link and use link_to when u want link to be click enabled. you can use instance variables to control what to render.

2) or use Javascript as suggested.

Use 2 if you want to dynamically do it.

You may use conditional link_to:

<%=
 link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
   link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user })
 end
%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM