Dercni
Dercni

Reputation: 1224

Rails AR record includes 'new' unsaved record

I have a view for an 'article' show action.

Articles have comments.

The view displays: a) article b) comments c) new comment form

My controller is action is:

def show
  @article = Article.find(params[:id])
  @comments = @article.comments
  @comment = @comments.new
end

The view displays the comments using a partial.

<%= render @comments %>

When looping through @comments I am finding the list also contains the new record from the controller action. I can avoid displaying this row using:

<% if !comment.new_record? %>
  ...
<% end %>

Am I doing this wrong or is this the expected behaviour?

Upvotes: 1

Views: 121

Answers (1)

Mike S
Mike S

Reputation: 11409

Yes it is expected because of how you are creating the new Comment. You are basically adding a new empty Comment to your @article.comments before you render them in the view. Your solution makes sense but alternatively you could avoid the issue by not assigning the @article to the new @comment inside your controller show action.

So instead of @comment = @comments.new you would do @comment = Comment.new. Then, inside your form for the @comment you would add a field for the article_id.

<%= f.hidden_field :article_id, :value => @article.id %>

This will allow you to maintain the relationship in your Comment.create action.

Upvotes: 1

Related Questions