铁轨授权?检查模型与控制器

发布于 2024-10-14 14:14:06 字数 259 浏览 4 评论 0原文

我正在对 user 模型进行检查,以确定她/他是否有一个或多个 task_list,如果她有多个 task_list,则允许她删除它,否则抛出异常。我基本上在用户模型中有一个名为 delete_list 的方法,以允许快速删除,例如 user1.delete_list(list1)

我正在争论是否将检查放在 CanCan 中,它将作为之前的应用控制器上的过滤器或是否也将其包含在用户模型中。推荐的做法是什么?

I am doing a check on a user model to determine whether s/he has one or more task_list, if she has more than one task_list only then she is allowed to delete it, otherwise an exception is thrown. I basically have an method called delete_list in the user model to allow for short hand deletions such as user1.delete_list(list1)

I am debating whether to put the check in CanCan where it would be apply as a before filter on the controller or whether to have it in the user model as well . What is the recommended practice?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸢与 2024-10-21 14:14:06

我认为一个好的 DRY 方法是在模型中创建一个方法来测试是否允许删除。然后使用控制器或ability.rb 中的该方法。恕我直言,我认为当您将来有可能更改为不同的权限系统时,将复杂的权限/业务逻辑与 CanCan 分离会更好。

在您的模型中:

def can_destroy_list(list)
   ... Do check here ....
end

在ability.rb 中

can :destroy, List do |list|  
    user.can_destroy_list(list)
end  

您的控制器和视图还可以直接在模型实例上使用 can_destroy_list if nessary 或使用: if can? :销毁,@列表

I think a good DRY approach to this would be to create a method in your model that tests whether a delete is allowed. Then use that method from your controller or from ability.rb. IMHO I think having complicated permission/business logic decoupled from CanCan is better when there is a chance you might change to a different permission system in the future.

In your model:

def can_destroy_list(list)
   ... Do check here ....
end

In ability.rb

can :destroy, List do |list|  
    user.can_destroy_list(list)
end  

Your controller and views can then also use can_destroy_list directly on the model instance if nessary or use: if can? :destroy, @list

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文