views:

66

answers:

2

Has anyone run into this problem?

I have a collection of comments that I loop through in the view as normal:

<% for comment in @post.comments %>
  <%= comment.body %>
<% end %>

But I also have a form to add a comment, but it seems that if I use @post.comments.build instead of Comment.new in the controller, that it created a blank instance of a 'comment' in the loop.

I would prefer to use .build not .new Has anyone encountered this? Is there a hack?

Thanks

+1  A: 

Funny you mention, I encountered this a few days ago.

I ended up going with Model.new but you could also try reloading the association after you call build.

@post.comments(true) will reload it. (You may also write @post.comments(:force_reload) for readability.)

An alternative to reloading might be calling the all named scope for the association, so @post.comments.all.

I think both will issue a new query anyway, but maybe they'll hit query cache.

kch
Nice one, I will give that a whirl. I would have thought that New and Build are close enough that it would happen to New, but I guess not.
Cameron
with build you create a new object from the association, part of the point is that it modifies the association. When you instantiate directly from the Comment class, it has no idea what associations are loaded or whether the object it's initializing has any possible relation to them.
kch
Worked a treat! Thanks.
Cameron
A: 
@comments = @post.comments
@comment  = @post.comments.build

That'll do it I think.

Ryan Bigg