2012-04-11 58 views
3

新しいコメント(多態性関係)を作成しようとすると、私はundefined method 'comments' for nil:NilClassを作成し続ける。私はこれに関する他のいくつかの質問を閲覧して、私のフォーム/コントローラに間違っているものを見つけることができないようです。find_commentable nilのための未定義メソッド `comments 'を返す:NilClass

はここにコメントのための私の一般的な部分である:

<%= form_for [@commentable, Comment.new] do |f| %> 
    <%= f.text_area :content %> 
    <%= f.submit "Post" %> 
<% end %> 

これは私のtraveldeal /ショーページにレンダリングされることに注意してください。フォームは上手くレンダリングされます。私はパラメータ[@commentable, @comment]を渡すためのform_forを変更した場合、私はNilClassのエラーundefined method MODEL_NAME」を取得:Class`

routes.rbを

resources :users 
resources :traveldeals 

resources :traveldeals do 
    resources :comments 
end 

resources :users do 
    resources :comments 
end 

はRailscastsはresources :traveldeals, :has_many => :commentsとして書かれた上記のがありますが、私はこれがあると信じて日付付きの構文。

comments_controller.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 

編集:上記のコードは、私の作品ように、解決策を追加しました。

答えて

1

form_for@commentableがありますが、その変数はどこに設定されていますか?それはどこにも設定されていないようだと私はエラーの原因だと思う。 my answeryour other questionも参照してください。

+0

私はあなたの他の答え、Mischaに案内してくれてありがとう。私はform_forが表示されているページに対して@commentableを定義しましたが、私のコメントが保存されないようにフォームを送信すると失敗したパス(current_user)に向かうようになりました。 – Huy

+1

"障害パス(current_user)"とはどういう意味ですか?あなたのコメントコントローラの 'before_filter'と関係があるかもしれません...あなたはまだログインしていますか? – Mischa

+0

私は自分のコメントが保存されていないことを意味しています(コントローラーに設定した方法、失敗した場合はcurrent_userにリダイレクトされます)。はい、コメントを作成しようとするとログインしています。 – Huy

関連する問題