首页 > 解决方案 > 如何迭代以查找表中是否存在任何记录

问题描述

Rails 的新手不确定我是否正在解决这个问题。所以我通过 sql lite 有两个表的数据库。酒吧和评论。bar 的 id 是评论的外键。

    create_table "reviews", force: :cascade do |t|
    t.string "picture"
    t.integer "bar_id"
    t.boolean "flagged_innapropriate"
    t.boolean "moderated"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["bar_id"], name: "index_reviews_on_bar_id"
  end

  create_table "bars", force: :cascade do |t|
    t.boolean "flagged_innapropriate"
    t.string "picture"
    t.boolean "moderated"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

我的导航栏上有一个部分,它在那里迭代并找到所有没有评论的栏。

    <div class="top-text">
  <p>Be the first to review these bars! </p>
</div>

<div id="norev-container">

  <% @bars.each do |bar| %>
    <% if bar.name? && !bar.flagged_innapropriate && bar.reviews.length == 0 %>

      <div class="bar-container">
        <%= link_to image_tag(bar.picture.thumb.url), %`/bars/#{bar.id}/reviews/new`%>
      </div>

    <% end %>

  <% end %>

</div>

<%= javascript_pack_tag 'norev' %>

这很好用。我也有一个导航栏。

<!DOCTYPE html>
<html>
  <head>
    <title>Bar Reviews</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= favicon_link_tag asset_path('favicon.ico') %>

</head>

  <body>
  <a href="/">
        <h1 id="title-top">
            Bar Reviews
        </h1>
      </a>
    <header>
      <nav class="navBar">
        <%= link_to "Home", root_path %>
        <%= link_to "Bars", bars_path %>
        <%= link_to "No Reviews", bars_norev_path %>
        <%= link_to "About", pages_about_url %>
      </nav>
    </header>

    <%= yield %>
  </body>

</html>

当没有没有评论的栏时,我希望隐藏“无评论”页面的链接。但是我无法理解如何遍历表格来找出这一点。有人指出我正确的方向吗?

标签: ruby-on-railsrubysqlite

解决方案


这通常是您想要对数据库查询执行的操作。不是通过遍历 Ruby 表中的所有记录。

可以使用左外连接来获取连接表中没有行的记录:

@bars = Bar.left_joins(:reviews)
           .where(flagged_innapropriate: false) # make sure you add a default to the column!
           .where.not(name: nil) # smelly - this should be handled by a validation?
           .where(reviews: { id: nil })

推荐阅读