Neil Neil - 7 months ago 12
Ruby Question

Rails iterate over only the persisted records associated to an object

I have something like this in my

show
action:

def show
@blog = Blog.find(params[:id])
@new_comment = @blog.comments.build
end


Now in the view I do two things:


  1. I render the
    _form.html.erb
    for the
    Comment
    so that the user can add a comment to this blog

  2. I want to be able to iterate over the existing comments for this blog in order to display them.



I am having problems with number 2. The issue is that as I iterate over the associated
comments
with this:

<% @blog.comments.each do |comment| %>


It is grabbing that
@new_comment
while iterating over the associated blogs. How can I exclude that built-but-not-yet-persisted
@new_comment
?

It would be nice if something like
@blog.comments.each_with_id
worked, or even
@blog.comments.persisted.each
. Ultimately I only want to iterate over the persisted
comments
associated to this
blog
.

I would prefer not to have to nest a conditional that asks if the comment is
persisted?
. I'm hoping there is an iterator out there for my current situation that just grabs the persisted records.

Answer

How about if you create the new comment without using the association to the blog instance? Then it won't show up when you iterate through @blog.comments.

def show
  @blog = Blog.find(params[:id])
  @new_comment = Comment.new(blog: @blog)
end
Comments