In my application, I have an user model/controller. An user can have multiple videos, images and blog items. User, and the items can have comments. So I’ve got the following controllers
- user
- user/comments
- user/picture
- user/picture/comments
- user/video
- user/video/comments
- user/blog
- user/blog/comments
The problem is, all the comments controllers are almost identical, and the code is becoming hard to manage. Now I’d like to specify a central place, e.g. a app-level CommentsController, which would have the methods to be called from sub-controllers.
What is the best way to do that?
How would for example the following code look after such a change:
class User::Picture::CommentsController < ApplicationController
def delete_all
@user = User.find(params[:user_id])
@picture = @user.pictures.find(params[:picture_id])
if @picture.has_access(current_user)
@picture.comments.destroy_all
redirect_to :back, :notice=>t(:actionsuccesful)
else
redirect_to :back, :alert=>t(:accessdenied)
end
end
end
The @user && @picture initializations are same among different methods (destroy, delete_all, create, index). Could they be moved into a before_filter which would be a sub-controller specific? And then, delete_all would be implemented in the CommentsController?
If the code is that generic, two options:
1) a module including shared methods
Example:
2) subclassing comment controllers from one controller
Example: