Search code examples
ruby-on-railsjquery-file-upload

Insert on controller action into another controller action


I am trying to add a controller action into another controller actions because I have an index page that lists a bunch of files. On that same page, I have a file upload sheet and I would like to call the document#new controller#method with the Home#index controller method. I tried include, but it gave me a uninitialized constant HomeController::DocumentController error. Any help appreciated.

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

Solution

  • You can store actions in a common module, and include that module into whatever controller needs it:

    # 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