使用 rails 4.0.0,嵌套多态路由路径(和 URL)生成失败。IE:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
class Image < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
路线:
resources :articles, :except => [:destroy] do
concerns :commentable
end
resources :images, :except => [:destroy] do
concerns :commentable
end
concern :commentable do
resources :comments, :only => [:create, :update, :show]
end
在某处的视图中:(假设评论是数据库中保存的评论)
= polymorphic_path([comment.commentable, comment])
应该输出类似的东西(假设 comment.commentable 是一篇文章):
/articles/1/comments/1
根据 PolymorphicRoutes 模块 (actionpack-4.0.0/lib/action_dispatch/routing/polymorphic_routes.rb) 中的注释,这种语法应该可以工作(除非我读错了)。
# polymorphic_url(post) # => "http://example.com/posts/1"
# polymorphic_url([blog, post]) # => "http://example.com/blogs/1/posts/1"
# polymorphic_url([:admin, blog, post]) # => "http://example.com/admin/blogs/1/posts/1"
# polymorphic_url([user, :blog, post]) # => "http://example.com/users/1/blog/posts/1"
# polymorphic_url(Comment) # => "http://example.com/comments"
相反,我得到了这个例外:
ActionController::UrlGenerationError: 没有路由匹配 {:action=>"show", :controller=>"comments", :locale=>##, :id=>nil, :format=>nil} 缺少必需的键:[: ID]