【问题标题】:How do I merge parent array and one child with different attribute?如何合并父数组和一个具有不同属性的子数组?
【发布时间】:2017-01-11 22:20:14
【问题描述】:

我有 cmets 和喜欢 (acts_as_votable gem)。我想创建一个活动列表,并按 created_at 排序 cmets 和 updated_at 投票。

@activity_list = (@user.comments + @user.find_up_voted_items)

@user.find_up_voted_items - 不是喜欢,而是喜欢的元素。

我可以使用此代码找到updated_at 的投票时间:

@post.votes_for.up.where(voter_id: @user.id).first.updated_at

如何正确合并和排序?

【问题讨论】:

  • where(...).first 你可以在相同的条件下使用find_by(...)

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


【解决方案1】:

以下内容不一定是高性能的,因为它构建了一个数组而不是 ActiveRecord 关系。

@ativity_list = (@user.comments + @user.votes.up).sort{|x,y| x.created_at <=> y.created_at}.map{|x| x.is_a?(Vote) ? x.votable : x}

(@user.comments + @user.votes.up) 返回一个 cmets 和投票数组。

#sort{|x,y| x.created_at &lt;=&gt; y.created_at}created_at 字段使用数组排序

#map{|x| x.is_a?(Vote) ? x.votable : x} 将数组从 cmets / vote set 更改为 cmets / voted on set

【讨论】:

    猜你喜欢
    • 2020-07-06
    • 1970-01-01
    • 2018-04-08
    • 2021-11-11
    • 2021-05-02
    • 1970-01-01
    • 2018-11-24
    • 2013-01-03
    • 2015-02-20
    相关资源
    最近更新 更多