简体   繁体   中英

rails 3 rendering view without action

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 ?

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!

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM