Rails仅迭代与对象关联的持久记录 [英] Rails iterate over only the persisted records associated to an object

查看:70
本文介绍了Rails仅迭代与对象关联的持久记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表演动作中有这样的内容:

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. 我渲染 _form.html.erb 用于评论,以便用户可以向此博客添加评论

  2. 我希望能够遍历此博客的现有注释以显示它们。

  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.

我遇到数字 2 的问题。问题是,当我迭代与此相关的评论时:

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| %>

在迭代的同时抓到 @new_comment 在相关的博客上。我如何排除已构建但尚未持久的 @new_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?

如果像 @ blog.comments.each_with_id 之类的东西,甚至甚至 @ blog.comments.persisted.each 。最终,我只想遍历与该博客相关的持久性评论

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.

推荐答案

创建新评论而不使用与博客实例的关联?然后,当您通过 @ blog.comments 进行迭代时,它不会显示。

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

这篇关于Rails仅迭代与对象关联的持久记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆