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:
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:
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
:
Now you know how Rails can render implicit actions in your controller. Until next time!