【问题标题】:Create array from ActiveRecords Association CollectionProxy从 ActiveRecord 关联 CollectionProxy 创建数组
【发布时间】:2014-08-17 02:54:01
【问题描述】:

我有一个 has_many 主题的组模型。主题模型has_many 帖子。 我想为按 Post 属性:published_on 排序的组创建一个包含所有主题的数组。

在我的小组展示页面上,我有 @group.topics.collect {|x| x.posts },它返回一个 ActiveRecord::Associations::CollectionProxy 数组,其中每个元素都包含一个帖子对象数组。

[
[[topic1 post],[topic1 post],[topic1 post]],
[[topic2 post],[topic2 post],[topic2 post]],
[[topic3 post],[topic3 post],[topic3 post]],
]

如何创建一个按 :published_on 排序的帖子数组?

【问题讨论】:

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


    【解决方案1】:

    我认为

    group.topics.includes(:posts).order("posts.published_on").map(&:posts).flatten
    

    足够了。

    【讨论】:

    • 同意这个答案。我会使用 .pluck(:posts) 而不是 .map
    【解决方案2】:

    你也可以用正确的关系解决这个问题。

    在您的 Group 模型上,您可以执行以下操作:

    # you already have this relation
    has_many :topics
    # you add this
    has_many :posts, through: :topics
    

    through 使用topics 就像posts 的桥梁一样工作,并返回您的group 拥有的所有posts

    然后,您的查询看起来像 group.posts.order(:published_on)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 2020-12-14
      • 2017-11-12
      • 1970-01-01
      • 2019-01-20
      • 2018-10-04
      • 2020-12-04
      相关资源
      最近更新 更多