Rails:访问满足两个条件的记录

时间:2014-07-03 22:44:53

标签: ruby-on-rails activerecord where

我试图访问"客户"今天创建的记录。有点像:

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

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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

现在你可以运行

User.customers.today.count