google1254
google1254

Reputation: 157

Can't access doubly nested resource?

I have comments which belong to answers which belong to questions. I'm currently trying to show the comments but I get an error:

undefined method `comments' for nil:NilClass

apparently from this line <%= render @answer.comments %>

My form for comments looks like this

<%= form_for([@answer, @answer.comments.build]) do |f| %>

<p>
    <%= f.label :comment %>
    <%= f.text_area :comment, :cols => "50", :rows => "30"%>
</p>
<p>
    <%= f.submit "Submit Comment" %>
</p>

And my comments controller looks like this

def create
@answer = Answer.find(params[:answer_id])
@comment = @answer.comments.create(params[:comment])
    redirect_to answer_path(@answer)
end

Comment belongs_to answer and answer has_many comments. Thanks!

Upvotes: 0

Views: 39

Answers (1)

rlecaro2
rlecaro2

Reputation: 755

You should create the comment as itself and relate it to your answer:

@comment = Comment.create(answer_id: params[answer_id])

GL & HF.

Upvotes: 1

Related Questions