Reputation: 11206
I keep getting a undefined method 'comments' for nil:NilClass
in my create method when I try to create a new comment(polymorphic relationship). I've browsed several other questions regarding this and can't seem to locate what's wrong with my form/controller.
Here is my generic partial for comments:
<%= form_for [@commentable, Comment.new] do |f| %>
<%= f.text_area :content %>
<%= f.submit "Post" %>
<% end %>
Please note that this is rendered in my traveldeal/show page. The form renders fine. If I change the form_for to pass parameters [@commentable, @comment]
, I get the error undefined method
model_name' for NilClass:Class`
routes.rb
resources :users
resources :traveldeals
resources :traveldeals do
resources :comments
end
resources :users do
resources :comments
end
The Railscasts has the above written as resources :traveldeals, :has_many => :comments
, but I believe this is 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 the solution so the code above works for me.
Upvotes: 3
Views: 967
Reputation: 43298
You have @commentable
in your form_for
, but where is that variable set? It seems to be set nowhere and I think that is the cause of the error. Also see my answer to your other question.
Upvotes: 1