これらのポリモーフィックな関連付けを完全に機能させるのに少し問題があります。私はこのチュートリアルwww.railscasts.com/episodes/154-polymorphic-associationに従いましたが、新しい投稿を作成するときにパス/ controller / ID#/commentsである場合にのみ機能するようです。/ controller / ID#で部分的なコメントフォームをレンダリングしようとすると、コメントの作成時に次のエラーが発生します。
undefined method `comments' for #<ActiveSupport::HashWithIndifferentAccess:0x10341b2d0>
私は3つのモデルを持っています:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments, :as => :commentable
end
class Article < ActiveRecord::Base
belongs_to :user
has_many :comments, :as => :commentable
end
これが/articles/#{ID}に対する私の見解です
<%= @article.title %>
<%= @article.content %>
<%= @article.user.login %>
<%= link_to 'Edit Article', edit_article_path(@article) %>
<h2>Comments</h2>
<%= render "comments/comments" %>
<%= render "comments/comment" %>
そして、ここに私のコメントの一部があります:
<div class="post_comment">
<%= form_for [@commentable, Comment.new] do |f| %>
<%= f.text_area :content %>
<%= f.submit "Post" %>
<% end %>
</div>
コメントコントローラのcreateメソッドは次のとおりです。
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
@comment.user_id = current_user.id
if @comment.save
redirect_to :id => nil
else
flash[:notice] = "something went wrong"
redirect_to @commentable
end
end
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
end
私は問題が何であるかを理解していると思いますが、問題を修正する方法がわかりません。このフォームは@commentableを探していますが、パスがネストされていない場合、@ commentableを見つけることができません(間違っている可能性があります)。
これが私のルートです:
devise_for :users do
get "login", :to => "devise/sessions#new"
get "register", :to => "devise/registrations#new"
end
resources :posts do
resources :comments
resources :tags
end
resources :articles do
resources :comments
resources :tags
end
resources :users do
resources :articles
resources :comments
resources :tags
resources :posts
end
resources :comments
root :to => "home#index"
end