Reputation: 17
I have comments on my post and I can display my comments first and form for writing comments after, but cannot display my form first and comments after. I'm pretty certain that the reason begind that is the .build:
<%= form_for([@question, @question.replies.build]) do |f| %>
So inside this form you just enter the comment body and click submit.
The displayed data is: commenter (user who commented), body of the comment and created_at.
The error I get is:
undefined method `first_name' for nil:NilClass
and the extracted source is:
<%= render @question.replies%>
<% @question.replies.each do |reply| %>
<div class="reply">
<p><%= link_to reply.user.first_name, user_profile_path(reply.user) %> says:</p>
<p><%= reply.body %></p>
<p>Answered <%= time_ago_in_words(reply.created_at) %> ago</p>
<% if current_user==reply.user %>
Upvotes: 0
Views: 46
Reputation: 17
The solution to this is that you have to check if the reply is nil before displaying anything.
<% @question.replies.each do |reply| %>
<% unless reply.user.nil? %>
Upvotes: 0
Reputation: 899
you should have some sort of @current_user available to you right?
So try doing something like this
<%= form_for([@question, @question.replies.build.tap{|a| a.user = @current_user}]) do |f| %>
The issue is that the comment that you are building with the form_for has a nil user value.
Upvotes: 0