0

I'm having trouble defining a Rails 'new' route for a model that takes a param to another model to which it will be linked. We have a legacy URL structure in place, so unfortunately a nested resource route won't work here.

I'd like to define the "create a new review" URL as /reviews/new/1234, where 1234 is the book_id that the soon-to-be-created Review should reference.

My routes (snipped for brevity) are defined as:

get    '/reviews/:book_id'          => 'reviews#index',   :as => 'reviews_path'
get    '/reviews/new/:book_id', :to => 'reviews#new',     :as => 'new_review_path'
post   '/reviews/:book_id'          => 'reviews#create'
get    '/reviews/:book_id/:id'      => 'reviews#show'
get    '/reviews/:book_id/:id/edit' => 'reviews#edit',    :as => 'edit_review_path'
delete '/reviews/:book_id/:id'      => 'reviews#destroy'

rake routes | grep review returns:

      reviews_path GET    /reviews/:book_id(.:format)                                              reviews#index
   new_review_path GET    /reviews/new/:book_id(.:format)                                          reviews#new
                   POST   /reviews/:book_id(.:format)                                              reviews#create
                   GET    /reviews/:book_id/:id(.:format)                                          reviews#show
  edit_review_path GET    /reviews/:book_id/:id/edit(.:format)                                     reviews#edit
                   DELETE /reviews/:book_id/:id(.:format)                                      reviews#destroy

In my view template I have:

<%= link_to 'new review', new_review_path(book_id: @book.id) %>

which fails with:

ActionView::Template::Error (undefined method `new_review_path' for #<#<Class:0x007f818f7117c8>:0x007f818f70e208>):

For completeness, my Review model looks like:

class Review < ActiveRecord::Base    
  attr_accessible :book_id, :title, :content, :tags
  belongs_to :book
end

1 Answer 1

1

Remove the _path from the end of the :as conditions on your routes. Right now it's looking for new_review_path_path.

Documentation is here for using as.

Sign up to request clarification or add additional context in comments.

1 Comment

No worries man - I have the markdown syntax for facepalm.jpg as a macro as I use it several times an hour, so I don't remember. :) Sometimes you just need extra SO eyes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.