sql - 在 Rails Controller 方法中使用 .where

标签 sql ruby-on-rails postgresql

我有一个统计页面,目前有一个 Items Bought 和一个 Items Sold 表。 Items Bought 表工作正常,但我在使用 Items Sold 表时遇到了一些问题。我的数据库中有一个 bool 值 SOLD,我希望显示所有标记为 TRUE 的项目的计数。当前的 .where 语句也有日期语句,我不确定如何将它们合并在一起并出错。

items_controller:

def statistics
  @items = Item.all
  @items_day = Item.all.where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_day, Time.zone.now.end_of_day)
  @items_week = Item.all.where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_week, Time.zone.now.end_of_week)
  @items_month = Item.all.where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_month, Time.zone.now.end_of_month)

  @items_sold = Item.all.where(:sold => true)
  @items_sold_day = Item.all.where(:sold => true 'created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_day, Time.zone.now.end_of_day)
  @items_sold_week = Item.all.where(:sold => true 'created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_week, Time.zone.now.end_of_week)
  @items_sold_month = Item.all.where(:sold => true 'created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_month, Time.zone.now.end_of_month)
end

statistics.html.erb

<h3 id="subtitle">Items Bought</h3>
<table align="center" style="width: 95%" class="table table-striped table-bordered">
  <thead>
    <tr>
      <th>Total</th>
      <th>Today</th>
      <th>Week</th>
      <th>Month</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td><%= number_with_delimiter(@items.count) %></td>
      <td><%= @items_day.count %></td>
      <td><%= @items_week.count %></td>
      <td><%= @items_month.count %></td>
    </tr>
  </tbody>
</table>

<h3 id="subtitle">Items Sold</h3>
<table align="center" style="width: 95%" class="table table-striped table-bordered">
  <thead>
    <tr>
      <th>Total</th>
      <th>Today</th>
      <th>Week</th>
      <th>Month</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td><%= number_with_delimiter(@items_sold.count) %></td>
      <td><%= @items_sold_day.count %></td>
      <td><%= @items_sold_week.count %></td>
      <td><%= @items_sold_month.count %></td>
    </tr>
  </tbody>
</table>

最佳答案

您可以链接多个 where 语句:

Item.where(:sold => true).where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_day, Time.zone.now.end_of_day)

关于sql - 在 Rails Controller 方法中使用 .where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40745404/

相关文章:

mysql - 哪种数据库和哪种索引最适合这种情况?

django - 在 dockerized 项目上运行 Django 迁移

sql - sys.columns.max_length 的替代方案

具有专门结果排序的 SQL 查询

mysql - 如何对所有标题进行求和,即使其他标题为空

mysql - Ruby on Rails MYSQL 查询

sql - 如何在 SQL 中比较 COUNT 个组的百分比?

sql - 如何以字符串格式检索 sql server SID?

ruby-on-rails - 是否可以使 Ohm for Ruby 中的整个对象的内容过期?

ruby-on-rails - 单页应用程序上的cancan