如何抽象多个控制器之间共享的泛型代码



在我的应用程序中,我有一个用户模型/控制器。一个用户可以拥有多个视频、图像和博客项目。用户,并且项目可以有注释。所以我有以下控制器

  • 用户
  • 用户/评论
  • 用户/图片
  • 用户/图片/评论
  • 用户/视频
  • 用户/视频/评论
  • 用户/博客
  • 用户/博客/评论

问题是,所有注释控制器几乎相同,并且代码变得难以管理。现在我想指定一个中心位置,例如应用程序级别的 CommentsController,它将具有从子控制器调用的方法。

最好的方法是什么?

例如,以下代码在此类更改后将如何查看:

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

@user&&@picture初始化在不同的方法(销毁,delete_all,创建,索引)中是相同的。是否可以将它们移动到特定于子控制器的before_filter中?然后,delete_all将在评论控制器中实现?

如果代码是通用的,则有两个选项:

1) 包含共享方法的模块

例:

module CommentsActions
  # actions, methods
end
class User::Picture::CommentsController <ApplicationController
  include CommentsActions
  #your additional actions
end

2) 从一个控制器子类化注释控制器

例:

class CommentsController < ApplicationController
  # actions, methods, filters etc...
end
class User::Picture::CommentsController < CommentsController
  #your additional actions
end

最新更新