0
votes

Have a show action on a ticket that pulls in a list of comments on the ticket. My goal is to display the list of ticket comments and then above it give the option for someone to add a comments.

This works when the form is below the list of comments, however when i put the above the comments, i get an error in the render of the comments saying that the record has no user id. Almost like the @comments in my ticket controller is somehow getting this new thing added from the form even though it is instantiated before the render of the form.

Here are my partials and controller. The error when the form is displayed first is "unable to find user_id = 0" That is due to the comments.commenter, which looks for the name of the person submitting the comment.

Ticket Controller

def show
  @ticket = Ticket.find(params[:id])
  @comments = @ticket.comments
end

tickets/show - The form is in here twice, but i only put it in once when trying to get this to work. I want it to work in the top spot.

<div class="widget-content nopadding">
  <ul class="new-comment">
    <%= render "comments/form" %>  --- Does not work here
  </ul>
  <ul class="recent-comments">
    <%= render @comments %>
  </ul>
</div>
<%= render "comments/form" %>  --- Works here, 

comments/form

<%= form_for([@ticket, @ticket.comments.build]) do |f| %>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

comments/comment

<li>
  <div class="comments">
    <span class="user-info"> User: <%= comment.commenter %> </span>
    <p>
      <strong>Comment:</strong>
      PUBLIC: <%= comment.try(:content) %>
    </p>
   </div>
</li>

1
are you getting any error message?Arivarasan L
ActiveRecord::RecordNotFound at /tickets/6 Couldn't find User with 'id'=0Austio
The error is on the 3rd line of the comments/comment view where it calls commenter. Because this is being built by ticket it doesn't have a user id associated with it yet. I guess i could just initialize it with a user ID but wanted to get to the base reason for it being off from what i expected.Austio

1 Answers

1
votes

Do you have a default set on the comment user_id to 0? What's happening is the form is building a new comment on the ticket. So i think that is getting rendered in the collection partial in addition to what the ticket already had. With the user_id set to zero, the comment.commenter tries to do the where id = 0, and it blows up.

So if you do have a default on that column, remove it. Foreign keys should default to nil.

The @comments is likely lazy loaded, that's why the _comment partial can be effected. @comments was not invoked until you have the second render. To avoid this, you can switch the @comments in the controller to:

@comments = Comment.where(ticket_id: params[:id])

Hope this made sense. Let me know if the default is the case. It's just a hunch :)