在Rails控制器方法中使用.where

时间:2016-11-22 15:12:40

标签: sql ruby-on-rails postgresql

我有一个统计信息页面,目前有一个Items Bought和一个Items Sold表。 Items Bought表工作得很好,但我对Items Sold表有一些问题。我的数据库中有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>

1 个答案:

答案 0 :(得分:3)

您可以链接多个where语句:

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