确保控制器的请求有效?

发布于 2024-11-14 13:44:29 字数 674 浏览 7 评论 0原文

在我的应用程序中,我有[例如]三个控制器:groupsforumsdiscussions

在我的 discussions_controller.rb 中:

def index
  @group = Group.find(params[:group_id])
  @forum = Forum.find(params[:forum_id])
  @discussions = @forum.discussions
  ...
end

例如,URL /groups/1/forums/1/discussions 呈现与 /groups/2/ 相同的页面论坛/讨论。这是否意味着在我的控制器中我必须附加类似 if @group.forums.to_a.include?(@forum) 的内容?这看起来很混乱而且不合轨道。我想我也可以创建一个私有方法,例如:

def has_forum
  deny_access unless @group.forums.to_a.include?(@forum)
end

但这会涉及代码重复......那么我是否缺少一些非常简单的东西?

谢谢

In my app, I have [for example] three controllers: groups, forums, and discussions.

In my discussions_controller.rb:

def index
  @group = Group.find(params[:group_id])
  @forum = Forum.find(params[:forum_id])
  @discussions = @forum.discussions
  ...
end

So, for example, the URL /groups/1/forums/1/discussions renders the same page as /groups/2/forums/discussions. Does this mean that in my controllers I'll have to append something like if @group.forums.to_a.include?(@forum)? This seems messy and non-rails. I guess I could also create a private method like:

def has_forum
  deny_access unless @group.forums.to_a.include?(@forum)
end

But this would involve code duplication... so is there something really simple I'm missing?

Thanks

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

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

发布评论

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

评论(1

镜花水月 2024-11-21 13:44:29

假设您的意思是 /groups/1/forums/1/discussions 呈现与 /groups/2/forums/1/discussions 相同的内容(即在两个网址中指定forum_id),那么您可以尝试以下操作:

def index
  @group = Group.find(params[:group_id]
  @forum = @group.forums.find(params[:forum_id])
  @discussions = @forum.discussions
  ...
end

这应该抛出一个 ActiveRecord ::RecordNotFound 如果您尝试访问错误组的论坛。但是,如果用户不属于该组,您应该拒绝访问。

Assuming you meant that /groups/1/forums/1/discussions renders the same contents as /groups/2/forums/1/discussions (i.e. specifying the forum_id in both urls) then you could try the following:

def index
  @group = Group.find(params[:group_id]
  @forum = @group.forums.find(params[:forum_id])
  @discussions = @forum.discussions
  ...
end

That should throw an ActiveRecord::RecordNotFound if you try and access a forum for the wrong group. You should, however, deny access if the user is not part of the group.

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