Neil Neil - 1 year ago 79
Ruby Question

Rails iterate over only the persisted records associated to an object

I have something like this in my


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

Now in the view I do two things:

  1. I render the
    for the
    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
with this:

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

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

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

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

Answer Source

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 = @blog)