Schrockwell
Schrockwell

Reputation: 838

Named routes not resolving in controller

I've set up a resource in routes.rb:

map.resource :papers

which is reflected in the output of rake routes:

 new_papers GET    /papers/new(.:format)                     {:controller=>"papers", :action=>"new"}
edit_papers GET    /papers/edit(.:format)                    {:controller=>"papers", :action=>"edit"}
     papers GET    /papers(.:format)                         {:controller=>"papers", :action=>"show"}
            PUT    /papers(.:format)                         {:controller=>"papers", :action=>"update"}
            DELETE /papers(.:format)                         {:controller=>"papers", :action=>"destroy"}
            POST   /papers(.:format)                         {:controller=>"papers", :action=>"create"}

The problem arises when I attempt to redirect to a named route within a controller action. This is an excerpt from the create action for the Paper resource. It should redirect the user to the show action of the paper controller on a successful save.

if @paper.save
  redirect_to @paper
else
  render :action => 'new'
end

The exception that arises is: undefined method 'paper_url', suggesting that the controller cannot see the named route. These helper methods will work in views, however.

As far as I can tell, this is the same way a Rails scaffold sets up a resource, so I can't find what's wrong. What am I missing here?

Upvotes: 0

Views: 283

Answers (2)

Tony Eichelberger
Tony Eichelberger

Reputation: 7142

It should be map.resources :papers

I could only get the error my copying out my route so I figured it must be a typo.

Upvotes: 2

astropanic
astropanic

Reputation: 10939

You have made a mistake

The scaffold for paper model will look like this:

   papers GET    /papers(.:format)                  {:controller=>"papers", :action=>"index"}
           POST   /papers(.:format)                  {:controller=>"papers", :action=>"create"}
 new_paper GET    /papers/new(.:format)              {:controller=>"papers", :action=>"new"}
edit_paper GET    /papers/:id/edit(.:format)         {:controller=>"papers", :action=>"edit"}
     paper GET    /papers/:id(.:format)              {:controller=>"papers", :action=>"show"}
           PUT    /papers/:id(.:format)              {:controller=>"papers", :action=>"update"}
           DELETE /papers/:id(.:format)              {:controller=>"papers", :action=>"destroy"}

have a look especially for the show method:

paper GET    /papers/:id(.:format)

instead of yours:

 papers GET    /papers(.:format)    

Upvotes: 1

Related Questions