I keep getting undefined method 'comments' for nil:NilClassin my create method when I try to create a new comment (polymorphic relationship). I looked through a few other questions about this and cannot find what is wrong with my form / controller.
Here is my general partial comment:
<%= form_for [@commentable, Comment.new] do |f| %>
<%= f.text_area :content %>
<%= f.submit "Post" %>
<% end %>
Please note that this appears on my traveldeal / show page. The shape looks great. If I change form_for to pass parameters [@commentable, @comment], I get the undefined methodmodel_name ' error for NilClass: Class`
routes.rb
resources :users
resources :traveldeals
resources :traveldeals do
resources :comments
end
resources :users do
resources :comments
end
Railscasts says above as resources :traveldeals, :has_many => :comments, but I believe this is a dated syntax.
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
Edit: Added solution, so the above code works for me.