【问题标题】:Sum ActiveRecord Relationship (Model + Model = Array?)求和 ActiveRecord 关系(模型 + 模型 = 数组?)
【发布时间】:2018-04-02 15:14:44
【问题描述】:

我正在尝试对两个活动模型关系求和并按created_at 对其进行排序。 狗和猫的总和构成一个数组。所以我尝试通过created_at.sort_by( &:created_at ) 对这个数组进行排序,但我得到了这个奇怪的错误:

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

comparison of ActiveSupport::TimeWithZone with nil failed

还有另一种最好的方法来总结两个活动记录关系并通过 created_at 对其进行排序?

非常感谢。

【问题讨论】:

  • dogscats ActiveRecord 型号吗?它们都有created_at 值吗?
  • 是的,他们都有 created_at 列。几个小时后,我解决了它:它适用于: dogs = Dog.where(user_id: current_user.id)

标签: ruby-on-rails arrays ruby activerecord model


【解决方案1】:

您的一个结果似乎有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)

【讨论】:

    【解决方案2】:

    我解决了这个问题。

    如果使用.where,一切正常。

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

    我不知道为什么,但就是这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多