视图中的 cancancan 身份验证
cancancan auth in the view
我在我的应用程序中添加了 cancancan 以进行授权,但我遇到了困难。
我有一个投票系统,您不能对自己的条目投票,但可以编辑、删除等。
所以我在能力 class 中创建了一个方块。
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,所以我可以对其进行投票,但是在第二个循环中相同的查询返回为 true 它应该做的但是链接仍显示在视图中?
总结一下,如果这有点令人困惑,两个不同帐户的两个条目,但投票链接出现在两个条目上。
像这样定义能力:
cannot :vote, Entry if user_id: user.id
文档:Defining-Abilities-with-Blocks#only-for-object-attributes
我在我的应用程序中添加了 cancancan 以进行授权,但我遇到了困难。
我有一个投票系统,您不能对自己的条目投票,但可以编辑、删除等。
所以我在能力 class 中创建了一个方块。
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,所以我可以对其进行投票,但是在第二个循环中相同的查询返回为 true 它应该做的但是链接仍显示在视图中?
总结一下,如果这有点令人困惑,两个不同帐户的两个条目,但投票链接出现在两个条目上。
像这样定义能力:
cannot :vote, Entry if user_id: user.id
文档:Defining-Abilities-with-Blocks#only-for-object-attributes