用户属于组织。用户可以查看所有组织,但只能查看组织中的用户。当用户查看组织时,我必须向视图中添加筛选逻辑,这样@organizations.users就变成了@organizations.users.select{|u| can?(:read, u)}。
是否有一种更透明或优雅的方法来管理这一问题?有没有办法摆脱select{|u| can?(:read, u)}或者把它移到干燥的地方?
相关代码:
class Organization < ActiveRecord::Base
has_many :users
...
end
class Ability
...
can :read, User, :organization => @user.organization
endorganizations/show.html.erb:(当前的、糟糕的版本)
<% if @organization.users.select{|u| can?(:read, u)}.any? %>
<h4>Contacts</h4>
<ul class="unstyled">
<% for user in @organization.users.select{|u| can?(:read, u)} %>
<li>
<%= link_to user, user, class: "user" %>
</li>
<% end %>
</ul>
<% end %>我想要更接近这个观点的东西:
组织/show.html.erb:
<% if @organization.users.any? %>
<h4>Contacts</h4>
<ul class="unstyled">
<% for user in @organization.users %>
<li>
<%= link_to user, user, class: "user" %>
</li>
<% end %>
</ul>
<% end %>更新:
我避免使用accessible_by,因为我有一个使用块的能力定义。
class Ability
...
can :read, User, :organization => @user.organization
can :read, User do |user|
user.is? :technical_contact
end
end我知道accessible_by可以使用块,但前提是提供了一个SQL片段。因为我的用户有许多角色,并且作为位掩码存储,所以我没有SQL片段。
发布于 2012-11-06 15:58:03
CanCan已经通过在活动记录模型上可用的accessible_by方法构建了对此的支持。
有关详细信息,请参阅https://github.com/ryanb/cancan/wiki/Fetching-Records。
https://stackoverflow.com/questions/13254639
复制相似问题