undefined method 'comments' for nil:NilClass
新しいコメント (ポリモーフィックな関係) を作成しようとすると、create メソッドでが取得され続けます。これに関する他のいくつかの質問を閲覧しましたが、フォーム/コントローラーの問題を特定できないようです。
コメントの一般的なパーシャルは次のとおりです。
<%= form_for [@commentable, Comment.new] do |f| %>
<%= f.text_area :content %>
<%= f.submit "Post" %>
<% end %>
これは、私の traveldeal/show ページでレンダリングされることに注意してください。フォームは正常にレンダリングされます。form_forを pass parameters に変更すると[@commentable, @comment]
、エラーundefined method
model_name' for NilClass:Class`が発生します
ルート.rb
resources :users
resources :traveldeals
resources :traveldeals do
resources :comments
end
resources :users do
resources :comments
end
Railscasts には上記のように書かれていますがresources :traveldeals, :has_many => :comments
、これは時代遅れの構文だと思います。
コメント_コントローラー.rb
class CommentsController < ApplicationController
before_filter :authenticate, :only => [:create, :destroy]
def new
@comment = Comment.new
end
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
@comment.user_id = current_user.id
if @comment.save
flash[:success] = "Successfully saved comment."
redirect_to root_path
else
redirect_to current_user
end
end
private
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
編集:上記のコードが機能するようにソリューションを追加しました。