我正在尝试将控制器操作添加到另一个控制器操作中,因为我有一个列出一堆文件的索引页。在同一页面上,我有一个文件上传表,我想用Home #index controller方法调用文档#new controller#method。我试过include,但它给了我一个未初始化的常量HomeController :: DocumentController错误。任何帮助表示赞赏。
class HomeController < ApplicationController
def index
if user_signed_in?
#show folders shared by others
@being_shared_folders = [] #current_user.shared_folders_by_others
#show only root folders (which have no parent folders)
@folders = current_user.folders.roots
#show only root files which has no "folder_id"
@documents = current_user.documents.where("folder_id is NULL").order("name desc")
include DocumentController::new
else
redirect_to sign_up_index_path
end
end
end
class DocumentsController < ApplicationController
def new
@document = current_user.documents.build
if params[:folder_id] #if we want to upload a file inside another folder
@current_folder = current_user.folders.find(params[:folder_id])
@document.folder_id = @current_folder.id
end
end
end
答案 0 :(得分:1)
您可以将操作存储在公共模块中,并将该模块包含在任何控制器所需的模块中:
# lib/common_actions.rb
module CommonActions
def index
# whatever
end
end
# app.controllers/home_controller.rb
class HomeController < ApplicationController
include CommonActions
end
# app.controllers/documents_controller.rb
class DocumentsController < ApplicationController
include CommonActions
end