user919635
user919635

Reputation:

Routing path in Rails 3.1

I am getting the following error in Rails 3.1:

undefined local variable or method `sitemap_home_path' for #<#:0x71152b0>

The error comes from the line:

It looks like I defined my route incorrectly. I routes.rb this route is defined as following:

root :to => 'home#index'

resources :home do
  collection do
    .....
    get :sitemap
    .....
  end
end

So, I am expecting my url to be http://localhost:3000/home/sitemap where sitemap is sitemap.html.erb file under views/home. Could someone explain to me why in this case sitemap_home_path does not get created?

It was working fine with the following Rails 2.1 declaration:

 resources :home, :collection => {...., :sitemap => :get }

Upvotes: 0

Views: 810

Answers (2)

Shirjeel Alam
Shirjeel Alam

Reputation: 154

To get the desired url_path i.e. sitemap_home_path your routes.rb should be like this:

resource :home
  collection do
    get :sitemap
  end
end

The reason for this is that home is a resource that is always looked up without an ID. Therefore in this case you should use a singular resource. Please refer to http://guides.rubyonrails.org/routing.html#singular-resources and the rails guides in general as the article on routing is quite comprehensive.

Upvotes: 2

Dylan Markow
Dylan Markow

Reputation: 124409

Running rake routes is a great way to see what Rails is naming your routes. With your code, you'll probably see something similar to this:

sitemap_home_index GET    /home/sitemap(.:format)  {:action=>"sitemap", :controller=>"home"}
        home_index GET    /home(.:format)          {:action=>"index", :controller=>"home"}
                   POST   /home(.:format)          {:action=>"create", :controller=>"home"}
          new_home GET    /home/new(.:format)      {:action=>"new", :controller=>"home"}
         edit_home GET    /home/:id/edit(.:format) {:action=>"edit", :controller=>"home"}
              home GET    /home/:id(.:format)      {:action=>"show", :controller=>"home"}
                   PUT    /home/:id(.:format)      {:action=>"update", :controller=>"home"}
                   DELETE /home/:id(.:format)      {:action=>"destroy", :controller=>"home"}

So, you want to use <%= link_to 'Sitemap', sitemap_home_index_path %>.

Upvotes: 0

Related Questions