[英]How can I enable admin to destroy the record when using CanCan?
My current code is just like this. 我当前的代码就是这样。
Only the user who posted can destroy his own records. 只有谁张贴能摧毁他自己的记录用户。
But I want to enable admin(user.id=1) to delete all the records. 但我想启用管理(user.id = 1)删除所有记录。
How can I change this? 我该如何更改? also view?
也查看? any smart way?
任何聪明的办法?
/models/ability.rb /models/ability.rb
def initialize(user)
if user
can :read, :all
can [:create, :destroy], Comment, {:user_id => user.id}
can [:destroy], Comment, {:commentable_id => user.id, :commentable_type => user.class.name}
can [:create, :update], Community, {:user_id => user.id}
else
can :read, :all
end
end
View 视图
<%= link_to 'x', polymorphic_path([@user, comment]),
:data => { :confirm => 'Do you want to delete?' },
:method => :delete, :disable_with => 'Deleting',
:remote => true,
:class => 'close'
if current_user && current_user.id == comment.user_id || current_user && current_user.id == comment.commentable_id %>
Here is what you need. 这就是您所需要的。 BTW it is bad idea to use
user.id == 1
to check for admin rights, probably better solution is to add boolean admin
field to User
model. 顺便说一句,使用
user.id == 1
来检查管理员权限是个坏主意,可能更好的解决方案是在User
模型中添加布尔值admin
字段。 If you don't want to do it, you can replace if user.admin?
如果您不想这样做,可以替换
if user.admin?
with if user.id == 1
. 与
if user.id == 1
。
def initialize(user)
guest_ability
user_ability(user) if user
admin_ability if user.admin? # or `if user.id == 1` if you don't want to add `admin` field
end
private
def admin_ability(admin)
can [:destroy], Comment
end
def user_ability(user)
can :read, :all
can [:create, :destroy], Comment, { :user_id => user.id }
can [:destroy], Comment, { :commentable_id => user.id, :commentable_type => user.class.name }
can [:create, :update], Community, { :user_id => user.id }
end
def guest_ability
can :read, :all
end
In your view: 您认为:
<% if can? :destroy, comment %>
<%= link_to 'x', polymorphic_path([@user, comment]),
:data => { :confirm => 'Do you want to delete?' },
:method => :delete, :disable_with => 'Deleting',
:remote => true,
:class => 'close' %>
<% end %>
In your ability file, you should make a distinction betyween the various roles a user can have, so you should add something like 在功能文件中,应区分用户可以拥有的各种角色,因此应添加以下内容:
if user.has_role? :admin
can :destroy, Comment
end
In your view, instead of "doing al the work yourself", as you're doing now, you should use the can? 在您看来,您应该使用罐子,而不是像现在那样“自己做”。 method, as follows
方法如下
if can? :destroy, comment
Using can? 使用可以吗? will use the directions you've described in your ability file.
将使用您在功能文件中描述的说明。 As simple as that!
就如此容易!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.