2017-10-21 85 views
0

我试图总结两个主动模型关系,并命令它由created_at。 狗和猫的总和是一个数组。所以,我试图解决这个数组由created_at.sort_by(&:created_at)但我得到这个奇怪的错误:Sum ActiveRecord关系(模型+模型=数组?)

dogs = current_user.dogs 
cats = current_user.cats 
total = (dogs + cats).sort_by(&:created_at) 

comparison of ActiveSupport::TimeWithZone with nil failed 

有总结两个活动记录关系,并责令由created_at另一种最好的方法?

非常感谢。

+0

“狗”和“猫”ActiveRecord模型?他们都拥有'created_at'值吗? – chrismanderson

+0

是的,他们有所有created_at列。几小时后,我解决了它: 它适用于: dogs = Dog.where(user_id:current_user.id) – rod

回答

2

你的一个结果有nilcreated_at好像,这就是为什么你得到这个错误。你可以做下面的过滤nil结果

dogs = current_user.dogs.where.not(created_at: nil) 
cats = current_user.cats.where.not(created_at: nil) 
sorted_results = (dogs + cats).sort_by(&:created_at) 

如果您想了解哪些结果具有created_atnil

nil_created_at_dogs = current_user.dogs.where(created_at: nil) 
nil_created_at_cats = current_user.cats.where(created_at: nil) 
0

我解决这个问题。

如果使用.where,所有工作正常。

dogs = Dog.where(user_id: current_user.id) 
cats = Cat.where(user_id: current_user.id) 
total = (dogs + cats).sort_by(&:created_at) 

我不知道为什么,但这是方式。