基本关联设置(注意,Customer 是 Person 模型的扩展):
Customer has_many :orders
Order belongs_to :customer
在 Customer.rb 中,我有以下类方法:
# SCOPE
def self.ordered_in_90_days
joins(:orders).where('orders.created_at > ?', 90.days.ago)
end
在我的测试中,我有以下代码创建一个新订单(自动创建一个客户感谢 FactoryGirl),然后使用上面定义的 Customer 模型的 self 方法:
it "finds customers who have ordered within the last 90 days" do
@order = FactoryGirl.create(:order, created_at: 50.days.ago)
@customer = @order.customer
Customer.count.should == 1 #passes
Order.count.should == 1 #passes
puts Customer.all.to_yaml #for debugging, see below
puts Order.all.to_yaml #for debugging, see below
Customer.ordered_in_90_days.should == [@customer] #fails! returns: []
end
正在创建客户和订单,但在方法调用(空数组)中没有返回任何内容。我错过了什么?
以下是有关工厂的一些附加信息:
FactoryGirl.define do
factory :customer do
first_name "Wes"
last_name "Foster"
type "Customer"
end
factory :order do
customer
end
end
这是 Customer 和 Order 的调试输出(请记住,Customer 是 Person 的扩展,因此您看到的是 person_id 而不是 customer_id):
---
- !ruby/object:Customer
attributes:
id: 1
first_name: Wes
last_name: Foster
type: Customer
created_at: 2013-09-16 21:54:26.162851000 Z
updated_at: 2013-09-16 21:54:26.162851000 Z
middle_name:
---
- !ruby/object:Order
attributes:
id: 1
person_id:
created_at: 2013-07-28 21:54:26.135748000 Z
updated_at: 2013-09-16 21:54:26.192877000 Z
(顾客