Rails 3 view without action

I defined routes for a specific action and created a link. I also created the corresponding views, but did not create the code defining the action method of the controller. However, the view is displayed when the link is clicked. This view is displayed without a valid presence.

Any explanation?

+6
source share
4 answers

Yes, the view will be displayed, even if the corresponding action is not present, it will work, since the routes are defined for them. But this is not a good practice!

+5
source

In order for Rails to display the view, you need to define a controller (optional with the appropriate 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 for the presentation.

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

+3
source

Rails does not expect you to define a controller action for each route in your config/routes.rb . As you probably know, you can define an action and also leave it blank:

 class PostsController < ApplicationController def index end end 

For any web application, it will be unusual for him to remain so, since the code for instance variables, database transactions, etc. ultimately fills most of your controller's actions. For a clean static page, the action must be defined, but must be blank.

+1
source

Even if you define filters for this action, it will also be executed regardless of whether you defined the action or not, and like Glen mentioned in his link, the rails automatically display the same name as the action inside the folder so named by the controller (which is present in the internal folder of views).

An empty action is equivalent to no action, but it is prescribed to define an action for some reason (for example, understandable and maintainable).

Link: here, this link says

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

Therefore, an explicit HTTP response is determined if you must change the default response.

0
source

Source: https://habr.com/ru/post/958622/


All Articles