Rails 3, polymorphic associations and matches without a route

I've been learning Rails for about 6 weeks now, so noob anyway!

I follow the Ryan Bates screencast in Polymorphic Associations, but when I try to go to / model / xx / comments, I get the error "No Route Matches".

After a two-day roundabout, I am completely stunned - everything seems to be in place.

Comment Model:

create_table "comments", :force => true do |t| t.text "content" t.integer "user_id" t.integer "commentable_id" t.string "commentable_type" t.datetime "created_at" t.datetime "updated_at" end 

Comment class:

 class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true end 

Other models:

 class ModelName < ActiveRecord::Base has_many :comments, :as => :commentable end 

routes.rb

 resources :modelname, :has_many => :comments 

comments_controller.rb

 def index @commentable = find_commentable @comments = @commentable.comments end private def find_commentable params.each do |name, value| if name =~ /(.+)_id$/ return $1.classify.constantize.find(value) end end nil end 

This is all according to the tutorial, but nonetheless returns "no route matches."

I tried alternative formatting of routes as nested resources.

 resources :modelname do |modelname| modelname.resources :comments end 

Explicitly defining comments in routes.rb

 resources :comments 

And various combinations of terms in routes. rb

 resources :modelname, :has_many => :commentables 

or

 resources :modelname, :has_many => :comments 

or

 resources :modelname, :has_many => :comments, :through => :commentable 

all without success.

Has anyone else come across this? I got lost as to where to start looking.

Thank you very much

+4
source share
2 answers

If you use Rails 3, routing is done differently. You define relationships in the model and map your routes to routes. Rb

In Rails 3, in order to do things, your routes.rb you must have this:

  resources :model do resources :comments end 

You should not indicate your relationship on the routes. Update your server and you should get a route like / model / id / comments / id

+4
source

In Rails 3, everything is a little different. To get the URL modelname/id/comments , you need the following route in routes.rb :

 resources :modelname do resources :comments end 

See this Rails Guide for more details and it goes a lot more.

+3
source

All Articles