簡體   English   中英

視圖中的cancancan auth

[英]cancancan auth in the view

我在我的應用程序中添加了cancancan以進行授權,而我則遇到了麻煩。

我有一個投票系統,您無法在自己的條目上投票,但是可以編輯,刪除等。

因此,我在能力類中創建了一個塊。

def initialize(user)
  if user.present?
    if user.admin?
      can :manage, :all

    else
      can :vote, Entry do |entry|
        user.id != entry.user_id
      end
      can :manage, Entry, user_id: user.id
      can :manage, Message, user_id: user.id
      can :manage, Profile, user_id: user.id
      can :manage, User, user_id: user.id

    end

   can :read, :all

  end
 end

我在這里叫罐頭嗎? 方法:

<% @entries.each do |x| %>

 <% if can? :vote, x %>
  <span class="text-green"> <%= link_to like_entry_path(x), method: :put, remote: true do %>
    <i class="fas fa-chevron-up"></i>
  <% end %>
  </span>
  <span class="badge" id="upvote-count<%=x.id%>"><%= x.get_upvotes.size%></span>
  <span class="text-red"> <%= link_to unlike_entry_path(x), method: :put, remote: true do %>
    <i class="fas fa-chevron-down"></i>
  <% end %>
  </span>
  <span class="badge" id="downvote-count<%=x.id%>"><%= x.get_downvotes.size%></span>
 <% else %>
  <i class="fas fa-chevron-up text-grey"></i>
  <span class="badge"><%= x.get_upvotes.size%></span>
  <i class="fas fa-chevron-down text-grey"></i>
  <span class="badge"><%= x.get_downvotes.size%></span>
 <% end %>
<% end %>

但是它仍然在不應該打印鏈接的時候?

調試時,在第一個條目上我檢查user.id != entry.user_id ,它返回為false,因此我可以對其進行投票,但是在第二個循環中,相同的查詢按原樣返回,但是鏈接仍然出現在視圖中?

總結一下,如果這有點令人困惑,則兩個條目分別輸入兩個不同的帳戶,但投票鏈接都出現在兩個條目上。

這樣定義能力:

cannot :vote, Entry if  user_id: user.id 

Doc: 定義具有功能的功能#only-for-object-attributes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM