空 div 与 ruby 一起出现。每个都在 HTML.erb 页面上可枚举。

Empty div is showing up with ruby .each enumerable on HTML.erb page.

我似乎无法弄清楚为什么我的 ruby .each 可枚举在我的对象数组为空的情况下生成一个空的 div ,或者如果我的 @posts 变量中有一个对象,则在底部添加一个空的 div。

这是我的 index.html.erb 页面:

<div id="post_feed">
<%if @posts.any?%>
  <%@posts.each do |p|%>
    <div class="post_text_box">
      <%=p.body%>
    </div>
  <%end%>
<%end%>
</div>

Post 控制器:

def index
    @posts = current_user.posts
    @new_post = current_user.posts.new 
  end

CSS:

#post_feed{
  margin-right:auto; 
  margin-left:auto; 
  width:400px; 
}

.post_text_box{
  padding:10px;
  margin:10px;
  background-color:#FFFFFF;
}

rails 控制台显示 1 个项目。

irb(main):014:0> Post.count
   (1.3ms)  SELECT COUNT(*) FROM "posts"
=> 1

Here is an image of the empty div.

即使尚未保存,Rails 正在考虑将 @new_post 作为 current_user.posts 的一部分,因此您在 post 处有一个空白@posts 列表的末尾。

它没有出现在数据库查询中,因为它还没有被保存。

根据您需要执行的操作,您可以将 @new_post 设为空 post (@new_post = Post.new) 并在保存时指定用户。

或者在你的 each 循环中,你可以在创建 div 之前检查 post 是否有主体,如果你可以依赖该检查来给你结果你想要:

<div id="post_feed">
  <%@posts.each do |p|%>
    <% if p.body %>
       <div class="post_text_box">
         <%=p.body%>
        </div>
     <%end%>
   <%end%>
 </div>

您不需要 if @posts.any? 检查,因为它总是评估为 true,因为使用 @new_post = current_user.posts.new.

创建了新的 post

并且通常在 ruby 中,您不需要在 运行 一个 each 循环之前检查数组是否为空,因为 each 循环不会用空数组做任何事情(或抛出错误)。

我明白了。在我的控制器中,我正在创建一个新对象但不保存它。我的 .each 迭代器将它识别为我的 @posts 对象数组中的一个对象,即使它没有保存。

我通过使用 new_record? 方法检查记录是否是新的来修复它。

<div id="post_feed">
<%if @posts.any?%>
  <%@posts.each do |p|%>
   <%if ! p.new_record?%>
    <div class="post_text_box">
      <%=p.body%>
    </div>
    <%end%>
  <%end%>
<%end%>
</div>