4

Rails 4.0.0 を使用すると、ネストされたポリモーフィック ルート パス (および URL) の生成に失敗します。いいえ:

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 があります。上部にパート 1 とパート 2 のリンクが表示されます。それが役に立てば幸い!

http://kconrails.com/2010/10/23/nested-comments-in-ruby-on-rails-1-models/

于 2014-08-08T17:14:58.520 に答える