Ruby on Rails: Can I route a request directly to a

2019-07-07 06:27发布

问题:

I have an admin section that has a sub-directory of the controllers directory. I.e., the directory app/controllers/admin/ holds a set of files, each containing a controller for handling a separate portion of the admin section.

Now, I want to create a very simple ''admin homepage'' that just says something a la "welcome to the admin section", but I want to avoid creating an entire controller for this purpose, or placing the "action" method for this view in some other, arbitrary controller.

So, the question is, is there a way to route ''directly to a view'' -- to route directly to an HTML file? (And, I don't want to route to an HTML file from a requested path like /some-file.html; I need to route from a path like /admin/.)

Asking this question here is hardly worth the time it takes to create a stub controller, but I'm sure I will have such a need again in the future.

回答1:

No, you can't. Why?

Design: It's just a violation of the MVC pattern Rails enforces you to use, for your own good. There is always a controller involved. And yes, even for such stub pages, a controller is required. Anyway, a few lines of code won't hurt you, and you'll love it again when you need to perform some access control.

Hope that answered your question :-)



回答2:

Like moritz says, you can't completely bypass the controller, but you do not necessarily have to create an entire controller just for this action. When I need a "dashboard" or "landing" type of page, I just add the action to my ApplicationController:

class ApplicationController < ActionController::Base
  def index
  end
end

Then put your page at app/views/application/index.html.erb

For your case, you can put an application_controller.rb in your app/controllers/admin/ directory, and do the same thing there.

I find that this is the perfect place for pages that fall outside of a resource.