Search code examples
ruby-on-railsrubyactioncontroller

Rails routing to another directory


Is there a way to direct a route to use a view that isn't in the expected folder?

Here's my problem... I'm creating a new view for my Reports, however I'm getting Missing template v1/reports/index error.

routes.rb

api_version(module: "V1", path: { value: "v1" }) do
  resources :reports, only: [:create, :index]
end

views/reports/index.html.erb

<h3>Just some test content</h3>

controllers/v1/reports_controller.rb

class V1::ReportsController < ApplicationController
  def index
   @company = current_user.company

   reports = if @company
    @company.reports.order("created_at DESC")
   else
    []
   end
  end
end

_navigation.html.erb

<%= link_to "Reports", v1_reports_path, role: "menuItem" %>

I used apipie to create some API for my application which has many of my controllers under a 'v1' directory within my app which is now causing some issues as I expand my app (I think). I don't want to have to redo the structure so hopefully there is a way to direct the route to use the view under views/reports/ instead of v1/reports/ which is what it is looking for which doesn't exist.

...or am I stuck with also having to create a `views/v1/reports/index.html.erb' file?


Solution

  • you should be able to just tell your controller what path to render

    class V1::ReportsController < ApplicationController
      def index
       @company = current_user.company
    
       reports = if @company
        @company.reports.order("created_at DESC")
       else
        []
       end
      end
      render '/path/to/views/reports/index.html.erb'
    end
    

    see section 2.2.3 and 2.2.5 of the docs for the render method

    although really, you should be using the directory rails wants you to. mainly because if there is a v2 controller made down the road, where would you put its views?