【问题标题】:count number of records in db with id of another table id?计算 db 中具有另一个表 id 的 id 的记录数?
【发布时间】:2013-09-10 15:05:37
【问题描述】:

我正在开发一个小型应用程序,我试图弄清楚要编写什么代码并进行研究,但我无法正确解决。

我的应用程序有“bins”,它们是选项卡,我有一个 bins 表,其中包含:id、:label_name 等...每个 bin 都有一个帖子。 DB 有一个带有 :id、:post_name 的表帖子,并且我创建了 :bin_id。我目前正在努力实现的目标,在我的设计中......每个 bin 显示它在侧边栏中的主页上有多少帖子(例如:News Bin --- 0,Sports Bin ---- 10,Art Bin - -- 12 等等..)

这是我在主页上找到的 bins 结构;

<% @bins_list.each do |bin| %>
    <div class="label %> active<% end %>"><span class="name">
</span>
<% else %><span class="num"><%= @bins.size %></span><% end %></div>
<% end %>

@bin.posts.size 的 "class="num" 行应该显示分配给该 bin id 的帖子数,方法是遍历 post 表并找到 :bin_id 列与 bin id 匹配的所有帖子在上面的代码中。

所以每个 bin 都有自己的 ID 并保存在 DB 中...用户将能够将帖子分配给该 Bin ID,并且帖子会将 bin id 保存在 Post 表 DB 中的 :bin_id 列下。

我已经完成了; 类 Bin

class Posts < ActiveRecord::Base
   belongs_to :bin
end

我已经在上面的视图代码中尝试过;

<span class="num"><%= @bin.posts.size %></span>

也试过了;

<span class="num"><%= @posts.where(:bin_id == :bin).size %></span>

也试过了;

<span class="num"><%= @posts.size %></span>

class HomeController < ApplicationController
    def index
       @posts = Post.find(params[:bin_id])
    end
end

但是这不起作用,在终端中,我知道“帖子”没有为类#blah blah 定义......我认为在模型中执行“has_many”和“belongs_to”应该相关?我想也有点困惑如何找到 Bins ID 并将其连接并通过 Post 搜索以查看 Bins ID 是否匹配,然后计算所有与该 ID 匹配的“真实”帖子并显示计数。

任何帮助我如何修改我的代码并构造它以使其工作?

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    尝试:

    【讨论】:

    • 在等待中发现; bin.id).count %> 但你的更干净,更容易阅读。天啊,我花了这么多时间试图弄清楚这一点,只是为了得出一个简短的结论。不知道为什么 bin.posts.size 在我尝试测试之前没有工作。也许我使用了 bins.posts.size 或一些小错误。感谢您的帮助!
    • 这可以解释这个问题。 :) 我开始认为我的 rails 配置对于不相关的 bin 和 post 模型是错误的。再次感谢!
    猜你喜欢
    • 2020-01-04
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多