【问题标题】:Empty div is showing up with ruby .each enumerable on HTML.erb page.空 div 在 HTML.erb 页面上显示为 ruby​​ .each 可枚举。
【发布时间】:2016-08-06 18:57:49
【问题描述】:

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

这是我的 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>

后控制器:

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.

【问题讨论】:

    标签: html ruby-on-rails ruby-on-rails-4 each enumerable


    【解决方案1】:

    尽管尚未保存,Rails 仍将 @new_post 视为 current_user.posts 的一部分,因此您的 @posts 列表末尾有一个空白帖子。

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

    根据您的需要,您可以将@new_post 设为空帖子 (@new_post = Post.new) 并在保存时分配用户。

    或者在您的 each 循环中,您可以在创建 div 之前检查帖子是否有正文,如果您可以依靠该检查来为您提供所需的结果:

    <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 创建的。

    通常在 ruby​​ 中,您不需要在运行 each 循环之前检查数组是否为空,因为 each 循环不会对空数组执行任何操作(或引发错误)。

    【讨论】:

    • 谢谢,约瑟夫。你的方式比我编造的烂摊子干净得多。
    【解决方案2】:

    我想通了。在我的控制器中,我正在创建一个新对象但没有保存它。我的 .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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      • 1970-01-01
      • 2015-02-21
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      相关资源
      最近更新 更多