【问题标题】:Rails: Retrieve latest timestamp from multiple children in associationRails:从关联的多个子项中检索最新时间戳
【发布时间】:2018-08-30 04:35:40
【问题描述】:

我的父对象有两个子对象。

它们每个都有 updated_at 和viewed_at 时间戳。

即具有一些 has_many/belongs_to 关联的人对象

Books: updated_at, viewed_at

Videos: updated_at, viewed_at

我想要一个只获取这四次中最新一次的查询。 即

Person.getAllBooksAndVideos.pluck(:updated_at, :viewed_at).sort{|a,b| [a.updated_at, a.viewed_at].compact.max <=> [b.updated_at, b.viewed_at].compact.max}.last 我不知道如何处理getAllBooksAndVideos.pluck(:updated_at, :viewed_at) 部分,非常非常欢迎任何建议。

【问题讨论】:

  • 我不确定,它是否有效,但你可以试试这个查询Person.joins(:books, :videos).select("persons.*, GREATEST(books.updated_at , books.viewed_at) FROM books, GREATEST(videos.updated_at , videos.viewed_at) FROM videos )

标签: ruby-on-rails postgresql rails-activerecord


【解决方案1】:

您可以将所有关联结果整理到一个数组中,并对其调用 sort_by。

result = (person.books + person.videos).sort_by {|x| [x.updated_at, x.viewed_at]}.last

那么您应该可以这样访问结果:
result.updated_at # This should give you your updated_at date
result.viewed_at # This should give you your viewed_at date

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    相关资源
    最近更新 更多