如果可以吗?不隐藏show.html上的链接



我刚刚安装了cancan,我遇到了一个快速的小问题。我应该能够使用if_can?应用操作来隐藏链接。当然,只有用户创建的信息才能查看编辑/删除链接。

我还没能找到有同样问题的人。如果有人能看一下,帮我一下,我将不胜感激。

show.html:

<div id="photos">
    <% for photo in @gallery.photos %>
    <div class="photo">
        <%= image_tag photo.image_url(:thumb).to_s %>
        <div class="name"><%= photo.name %></div>
        <div class="actions">
            <% if can? :update, @photo %>
            <%= link_to "edit", edit_photo_path(photo) %> |
            <% end %>
            <% if can? :remove, @photo %>
            <%= link_to "remove", photo, :confirm => 'Are you sure?', :method => :delete %>
            <% end %>
        </div>
      </div>
    <% end %>
    <div class="clear"></div>
</div>
<p>
  <%= link_to "Add a Photo", new_photo_path(:gallery_id => @gallery) %>
|
  <%= link_to "Remove Gallery", @gallery, :confirm => 'Are you sure?', :method => :delete %> |
  <%= link_to "View Galleries", galleries_path %>
</p>

ability.rb

class Ability
  include CanCan::Ability
  def initialize(user)
    can :read, :all 
  end
end

OK,每个控制器必须被授权。最简单的方法是从照片开始,并确保它不能被删除。您将需要这样的内容:

can :delete, Photo do |photo|
  question.try(:user) == user
end   
在你的能力范围内。在你的照片的控制器中,你需要输入load_and_authorize_resourceauthorize_resource

那么在您的视图中,您需要<%if can :remove, photo %>而不是<%if can :remove, @photo>。我觉得很奇怪,当你有<for photo in @gallery.photos %>

时,你试图使用@photo

我也经历过这个问题。解决办法很简单。Rb类执行如下操作

class Ability
  include CanCan::Ability
  def initialize(user)
  user ||= User.new # guest user (not logged in)
  if user.role == "admin"
    can :update, Photo, :user_id => user.id
  end 
end 

然后在index.html.erb中做如下操作

<% @photos.each do |photo| %>
 <%if can? :update, photo %>
  <!-- hide your links and buttons here-->
 <%end%>
<%end%>

注意:在"<%if can?":update, photo %>"写"photo"而不是"photo"或"@photo"。因为这里photo是一个变量它将在循环中迭代

最新更新