Forgot to define action - but no error! How is this possible?

One of my routes looks like this:

admin_pages_home GET /admin_pages/home(.:format)
admin_pages#home

In one of my views, I have a link to admin_pages_home_path, and clicking
on this link indeed works and renders admin_pages/home.html.erb, as we
can see from the logfile:

Started GET "/admin_pages/home" for 127.0.0.1 at 2014-09-08 15:32:41
+0200
Processing by AdminPagesController#home as HTML
  Rendered admin_pages/home.html.erb within layouts/application (7.6ms)

Now, the weird thing here is that I had forgotten to define a home()
function in AdminPagesController (and I also didn't put one in
ApplicationController). Actually, the only other home method I have is
in a completely unrelated controller.

I wonder how it can be, that clicking on the admin_pages_home_path link,
didn't raise an exception.

Ronald

This is expected behaviour. You can find out more about implicit rendering here: http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-by-default-convention-over-configuration-in-action

MM.

Hi Ronald,

Its not necessary to have declare an action in a controller for a particular view. If you look at MVC ( Model - View - Controller ). You only have to declare an action if you want to initialize an object which the view would use.

eg:

posts -> index action

@posts = Post.all

It is a good practice to declare all your objects in the action and use them in your views although you can still declare you objects in your views this way

erb:

<% @posts = Post.all %>

I hope that explains :slight_smile:

Cheers

Vivek

If you don't have a defined action, Rails looks for a corresponding template with the same name as the controller/action

If it finds one, it just renders that template. If it doesn't find one, it just raises a missing template error.

It's been like this since the dawn of Rails.

Muskalek wrote in post #1157141:

This is expected behaviour.

I see! Thank you for pointing it out!

At times, the plethora of automatisms found in Rails is a bit creepy
....

I always had the habit to explicitly define my actions, so I didn't
stumble over this one earlier.

Ronald