Reputation: 6075
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>
Upvotes: 0
Views: 1083
Reputation: 13621
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 :)
Upvotes: 1