我有两个型号
客户和交易
Customer
has_many :transactions
Transaction
belongs_to :customer
现在我需要所有拥有
的客户答案 0 :(得分:2)
扩展ScottJShea的答案,我会使用一些范围
scope :one_recent_transaction, :conditions => lambda {
includes(:transactions).where("transactions.date > ?", DateTime.now - 30.days).group("customer.id").having("COUNT(transactions.id) = 1")
}
scope :many_recent_transactions, :conditions => lambda {
includes(:transactions).where("transactions.date > ?", DateTime.now - 30.days).group("customer.id").having("COUNT(transactions.id) > 1")
}
然后像这样使用它们
one_transaction = Customer.one_recent_transaction
many_transactions = Customer.many_recent_transactions
答案 1 :(得分:0)
您想使用HAVING
子句。我建议(我猜测有点不完全了解你的模型):
@exactly_one = Customer.where("transaction_date between ? and >", Date.now, Date.now - 30).group("customer.id").having("count(transaction.id) = 1")
@exactly_one = Customer.where("transaction_date between ? and >", Date.now, Date.now - 30).group("customer.id").having("count(transaction.id) > 1")