确保控制器的请求有效?
在我的应用程序中,我有[例如]三个控制器:groups
、forums
和 discussions
。
在我的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您的意思是 /groups/1/forums/1/discussions 呈现与 /groups/2/forums/1/discussions 相同的内容(即在两个网址中指定forum_id),那么您可以尝试以下操作:
这应该抛出一个 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:
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.