15 Aug

Rails static pages - Rails Tricks Issue 15


Hi there,


This week I want to show you how I add static pages in a Rails application, since I just did this recently.


I like to put all of them into the same controller so they are nicely separated, so I generate a new controller called StaticPagesController. Then I add my routes:

cddf7ec0-3085-40df-98f7-8327175a2ff6.png 66 KB And I create my views in app/views/static_pages/. Since Rails 7.0, I can omit the controller methods, Rails will render the appropriate views regardless. That’s it. This would be today’s Rails trick, but since it would be super short, let’s dig into how Rails renders the views without the controller methods being defined.

As I found out, this feature called “implicit rendering”. What happens is, when Action Controller is processing a request, it is trying to find the appropriate method for the action it receives from the router:

4c4b8fa7-47e5-4c71-9c73-586be33505bc.png 99.2 KB This method is overridden in action_pack/lib/action_controller/metal.rb to check if there is any template available for the action, and if so, it renders the template, if not, it just renders a head: :no_content: 10246ea8-6ba3-41de-adeb-b6601c050338.png 637 KB Now you know how Rails can render implicit actions in your controller. Until next time!