【问题标题】:Rails acts_as_follower get posts of users I'm following AND my ownRails act_as_follower 获取我正在关注的用户和我自己的用户的帖子
【发布时间】:2013-10-12 12:55:31
【问题描述】:

我已经设法将我的帖子范围仅限于我使用以下代码关注的用户:

following_ids = current_member.following_members.map(&:id)
@statuses = Status.where(member_id: following_ids).order("created_at DESC")

但我还想添加我自己的帖子,但我无法完成此操作。所以基本上将该代码与该代码结合起来:

@statuses = @member.statuses.order('created_at desc').all

最好的方法是什么。

【问题讨论】:

    标签: ruby-on-rails controllers posts


    【解决方案1】:

    拉出两个对象数组并将它们展平。

    following_ids = current_member.following_members.map(&:id)  
    @statuses = Status.where(member_id: following_ids).order("created_at DESC")
    @statuses << @member.statuses.order('created_at desc').all
    @statuses = @statuses.flatten
    

    要按时间顺序查看列表,请调用 sort_by

    所以而不是

    @status = @statuses.flatten
    

    使用

    @status = @statuses.flatten.sort_by{ |status| status.created_at }
    

    【讨论】:

    • 这种方式将我关注的用户的所有状态叠加在我自己的所有状态之上。我希望它们根据创建的时间混合在一起。
    【解决方案2】:

    我发现我需要使用 push 而不是 flatten。

    @statuses = Status.where("member_id in (?)", following_ids.push(current_member.id)).order("created_at desc").all
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多