Search code examples
ruby-on-railsruby-on-rails-3model-view-controllercontrollers

Ensure that the controller's request is valid?


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


Solution

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