Search code examples
ruby-on-railsruby-on-rails-3routescontrollers

Controller method never gets executed although view is rendered fine


I have a strange problem with my Rails routing . I have a controllers called Page and a method called Page#dashboard

When I try to access /dashboard/1 the dashboard method of Page Controller never gets executed. But surprisingly the /pages/dashboard.html.erb is rendered fine .

Can someone explain me why ?

Code details as below . Thanks

Trying to access - /dashboard/1

Routes.rb

match '/dashboard/:id' => 'page#dashboard'

Page_Controller.rb

class PageController < ApplicationController

  before_filter :init

  private

  def init

    puts "init getting executed !!!!!!!!!"  #this gets printed on console

  end

  def dashboard

     puts "dashboard getting executed !!!!!!!!!" #this doesnt get printed on console


  end

end

viewPage - Pages/dashboard.html.erb

The logs are shown as below -

init getting executed !!!!!!!!!
Started GET "/dashboard/8" for 127.0.0.1 at 2012-06-03 00:04:40 +0800
Processing by PageController#dashboard as HTML
  Parameters: {"id"=>"8"}
  Rendered page/dashboard.html.erb within layouts/page (45.9ms)
Completed 200 OK in 180ms (Views: 133.6ms | ActiveRecord: 3.1ms)

Solution

  • First off, you don't have to define an action method. If all you want to do is render a template then as long as the template foo exists, rails will happily allow you to route to SomeController#foo.

    Secondly, for a method to be an action is has to be public. Your dashboard method is private so it doesn't count as an action and doesn't get executed. Since you have a dashboard.html.erb template, rails does however render that.