【问题标题】:Merging two ActiveRecord associations collections into single Association collection将两个 ActiveRecord 关联集合合并为单个关联集合
【发布时间】:2018-10-02 13:42:26
【问题描述】:

我有一个帖子模型,用户可以在其中添加类似于 facebook 的帖子。

在新闻源中,我想按照 created_at 的降序显示它们。

问题是

current_user.posts

返回他/她的帖子,而

current_user.networks.each {|network| network.connection.posts}

返回他的联系人的帖子。

我想结合这两个结果,这样我就可以写出类似的东西

all_posts.order(created_at: :desc)

或者有更好的方法吗?

编辑

有代码

user.rb

has_many :posts

post.rb

belongs_to :user

network.rb

belongs_to :user
belongs_to :connection, class_name: 'User'

其中网络模型是一个联合和自引用模型,具有 user_idconnection_id 列,当两个用户成为朋友时它会更新。

【问题讨论】:

  • post/connection/user 之间有什么关联?
  • @AndreyDeineko 用户的帖子和他朋友的又名连接的帖子之间的编号。
  • @AndreyDeineko 好的。我将使用代码编辑问题。
  • connection.rb 看起来如何?

标签: ruby-on-rails ruby postgresql activerecord


【解决方案1】:

试试:

user_post_ids = current_user.post_ids
connection_post_ids = []
current_user.networks.each do |network|
  connection_post_ids += network.connection.post_ids
end
post_ids = user_post_ids + connection_post_ids

all_posts = Post.where(id: post_ids).order(created_at: :desc)

【讨论】:

  • 好的。会试试的。
  • current_user.post_ids 工作,但对于 connection_post_ids 我得到未定义的方法 `post_ids' #<:connectionadapters::postgresqladapter:0x00007fba958160f8> 错误。
  • 嗨..它也可以使用以下代码进行连接: 其中 connection_post_ids = [] 声明为空数组。但是现在结果有两个数组 [[45,34,54,24,53]]。能否请您帮助如何删除一个数组。
  • 如果 array = [[45,34,54,24,53]] 然后调用 array.flatten 删除外部数组括号
猜你喜欢
  • 2016-05-02
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 2014-09-04
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多