【问题标题】:Rails: accessing records where two conditions are metRails:访问满足两个条件的记录
【发布时间】:2014-07-03 22:44:52
【问题描述】:

我正在尝试访问今天创建的“客户”记录的数量。大致如下:

@customersToday = User.where("created_at >= ?", Date.today,  user_type: 'Customer').count

如何在单个查询中执行此操作(有效)?

【问题讨论】:

  • 这不是一个单一的查询吗?
  • 这是一个单一的查询。也许改写你的问题?
  • 我的问题中的查询不起作用

标签: ruby-on-rails activerecord where


【解决方案1】:
@customersToday = User.where("created_at >= ? and user_type = ?", Date.today, 'Customer').count

【讨论】:

    【解决方案2】:

    您的应该在单个查询中运行,但您可以通过创建几个范围来简化它

    class User < ActiveRecord::Base
      scope :today, -> { where ["created_at >= ?", Date.today] }
      scope :customers, -> { where user_type: 'Customer' }
    end
    

    现在你可以运行了

    User.customers.today.count
    

    【讨论】:

    • 这给了我一个无方法错误。尝试了 User.customer.today.count 和 User.customers.today.count
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2016-03-23
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多