Rails 路由 devise_for / 资源 CRUD 重叠

发布于 2024-11-14 05:49:58 字数 414 浏览 3 评论 0原文

我已经为我的 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 技术交流群。

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

发布评论

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

评论(2

春风十里 2024-11-21 05:49:58

更好的做法可能是不要将所有物路由嵌套在用户下,而是将其单独作为 /possessions/1 并在您的所有物控制器中以限制当前用户的所有发现,即

def index
  @possessions = current_user.possessions
end

def edit
  @possession = current_user.possessions.find(params[:id])
  ...
end

:这样您就可以确保用户只能看到自己的物品,并且如果他们尝试访问其他人的物品,他们将收到 404。

继承资源使这变得非常容易,因此您可以像这样编写控制器代码:

class ProjectsController < InheritedResources::Base
  protected
    def collection
      @projects ||= end_of_association_chain.paginate(:page => params[:page])
    end
end

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.:

def index
  @possessions = current_user.possessions
end

def edit
  @possession = current_user.possessions.find(params[:id])
  ...
end

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:

class ProjectsController < InheritedResources::Base
  protected
    def collection
      @projects ||= end_of_association_chain.paginate(:page => params[:page])
    end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文