4

使用 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]

4

1 回答 1

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/

于 2014-08-08T17:14:58.520 回答