rails 3 rendering view without action

2020-07-07 05:17发布

问题:

I defined the routes for a particular action and created a link. I created the corresponding views too but did not code define the controller action method. Still the view is rendered on clicking the link. That is the view is rendered without the action actually being present.

Any explanations ?

回答1:

Yes, the view will be rendered even if no corresponding action is present, it will work as routes are defined for the same. But this is not a good practice!



回答2:

For Rails to render a view, you'll need to have defined a controller (not necessarily with a corresponding method), a route that references the view and the view. Adding a method to the controller is only necessary if you need to provide data to the view.

There's a pretty thorough explanation of this in http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-by-default-convention-over-configuration-in-action



回答3:

Rails does not expect you to define a controller action for every route in your config/routes.rb file. As you probably know you can define an action and also leave it empty like so:

class PostsController  < ApplicationController

  def index
  end

end

For any web application it will be unusual for it to stay this way as code for instance variables, database transactions and the like will eventually populate most of your controller actions. For a pure static page the action should still be defined but should be empty.



回答4:

Even if you define filters for that action, it will also execute irrespective of whether you have defined the action or not and as Glen mentioned through his link the rails automatically renders view of same name as that of action inside folder named as that of controller( which is present inside views folder ).

Empty action is equivalent to no action , but prescribed is to define action for some reasons (like understandably and maintainability ).

Reference : here in this link says

Note that the empty method from the example above would work just fine because Rails will by default render the new.html.erb view unless the action says otherwise

Hence explicit HTTP response is defined in case you have to change default response.