使用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 =&gt;“show”,:controller =&gt;“comments”,:locale =&gt; ##,:id =&gt; nil,:format =&gt; nil}缺少必需的键:[:id]
答案 0 :(得分:0)
我的评论模型中有这个
belongs_to :post
belongs_to :commentable, :polymorphic => true
has_many :comments, :as => :commentable
def post
return @post if defined?(@post)
@post = commentable.is_a?(Post) ? commentable : commentable.post
end
在我的帖子模型中
has_many :comments, :as => :commentable, :dependent => :destroy
在我的路线档案中
resources :posts do
resources :comments
end
resources :comments do
resources :comments
end
您可以查看本教程,它帮助我使用我的网站。模型的第一部分和控制器和路线的第二部分。您将在顶部看到第1部分和第2部分链接。希望它有所帮助!
http://kconrails.com/2010/10/23/nested-comments-in-ruby-on-rails-1-models/