在 Rails 中,授权用户访问模型的最佳实践是什么?
我使用 Devise 进行用户身份验证和基本身份验证。假设我已经定义了用户和汽车之间的两个相互关联。
- 用户
has_many :cars
- 汽车
belongs_to :user
用户 A 拥有一辆 id 为 1 的汽车,用户 B 拥有一辆 id 为 2 的汽车。
阻止用户 A 访问的最佳实践是什么/cars/2
的资源?我可以为每个控制器添加一个 before_filter :show、:edit、:update、:destroy,但这看起来很乏味且重复。有没有办法使用 Devise 或 CanCan 来实现此目的?
I'm using Devise for user authentication and basic authentication. Let's say I have defined two reciprocal associations between Users and Cars.
- User
has_many :cars
- Car
belongs_to :user
User A has a car with id 1, User B has a car with id 2.
What's the best practice for preventing User A from accessing the resource at /cars/2
? I could add a before_filter for :show, :edit, :update, :destroy to each controller, but that seems tedious and repetitive. Is there any way to use Devise or CanCan for this purpose?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 CanCan 来实现此目的,请在此处阅读更多相关信息 https://github.com/ryanb/cancan
将
load_and_authorize_resource
添加到控制器顶部后,您可以将以下行添加到您的能力模型中,以仅允许车主管理它
you can use CanCan for this, read more about it here https://github.com/ryanb/cancan
after adding
load_and_authorize_resource
to the top of your controlleryou can add the following line to your ability model to only allow the cars owner to manage it