Rails 路由 devise_for / 资源 CRUD 重叠
我已经为我的 User 类设计了工作,并且我正在尝试向用户控制器添加一些 CRUD 方法。我已经阅读过有关此路由的信息,只要 devise_for
出现在 resources
之前,它将优先,否则您将只能通过 /users/ 访问不存在的记录登录或其他什么。反正。
我有我的 CRUD 方法,甚至还有一些资源。假设用户有很多财产。我可以通过 /users/1/possessions/1 查看财产,但是当我尝试删除它时,我无权访问 Devise current_user 方法。我可以通过使用 params[:user_id] 查找用户,然后通过 params[:id] 查找它的财产来删除,但如果我只希望登录的用户能够删除他/她自己的财产,那么这并不真正安全。
如何在我的用户模型的 CRUD 方法中使用 Devise 的方法?
I've got devise working for my User class, and I'm trying to add some CRUD methods to the users controller. I've read about routing for this, and so long as devise_for
comes before resources
it will take precedences, otherwise you will only be accessing non-existent records via /users/sign_in or whatever. Anyway.
I have my CRUD methods working, and even some resources. Say users have many possesssions. I can view a possessions via /users/1/possessions/1, but when I try to delete it, I don't have access to the Devise current_user method. I could delete by looking up the User with params[:user_id], and then finding it's possessions by params[:id], but that's not really secure if I only want the logged in user to be able to delete his/her own possessions.
How can I use Devise's methods from within my User model's CRUD methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Ruby on Rails 的模型中使用“current_user”
http://rails-bestpractices.com/posts/47-获取模型中的当前用户
Using "current_user" in models in Ruby on Rails
http://rails-bestpractices.com/posts/47-fetch-current-user-in-models
更好的做法可能是不要将所有物路由嵌套在用户下,而是将其单独作为
/possessions/1
并在您的所有物控制器中以限制当前用户的所有发现,即:这样您就可以确保用户只能看到自己的物品,并且如果他们尝试访问其他人的物品,他们将收到 404。
继承资源使这变得非常容易,因此您可以像这样编写控制器代码:
A better practise might be to not nest the possessions route under user, instead have it on its own as
/possessions/1
and the in your possessions controller to scope all of your finds by the current_user i.e.:That way you can be sure that the user will only ever be able to see their own items, and they will receive a 404 if they tried to access someone else's possessions.
Inherited Resources makes this really easy to do, so you can code your controllers like this: