ruby-on-rails - 如何迭代以查找表中是否存在任何记录
问题描述
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 表中的所有记录。
可以使用左外连接来获取连接表中没有行的记录:
@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 })
推荐阅读
- php - PHP 如果时间是周末 EST 然后 X,否则 Y
- jestjs - 如何用 jest 测试议程作业?
- node.js - 被crontab启动后退出脚本
- javascript - 救援组/Petfinder jQuery API 请求
- python - Pytest 基于 mark.parameterize 值选择测试?
- python - python - 文件夹名称中的空格
- javascript - resx 文件字符串编码错误
- php - 如何从表中获取“id”到模态以使用 php 将其删除
- javascript - 根据用户指定的过滤器仅返回用户指定的列
- node.js - 运行 npm run dev 时 babel-watch server.js 失败