3

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 methodmodel_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

編集:上記のコードが機能するようにソリューションを追加しました。

4

1 に答える 1

1

あなたはあなたの中に持っ@commentableていますform_forが、その変数セットはどこにありますか? どこにも設定されていないようで、それがエラーの原因だと思います。あなたの他の質問に対する私の答えも見てください。

于 2012-04-12T02:29:39.860 に答える