【问题标题】:Rails select distinct association from collectionRails 从集合中选择不同的关联
【发布时间】:2018-09-28 03:41:56
【问题描述】:

假设我有一个模型 Post 和一个模型 User。给定一组帖子 (@posts),我怎样才能获得唯一作者?

这可行,但由于显而易见的原因很糟糕:@posts.map(&:author).uniq(&:id)

稍微好一点的方法是:User.where(id: @posts.pluck(:author_id))

有没有更好的办法?

【问题讨论】:

  • User.joins(:posts).where(posts: {id: @posts})

标签: ruby-on-rails activerecord


【解决方案1】:
User.where(id: @posts.select('distinct author_id'))

User.where(id: @posts.pluck('distinct author_id'))

将在 SQL 查询中应用“DISTINCT”(不是 Array#uniq)

注意:

如果您尝试获取用户 activerecord 关系,则“不同”是无用的,因为“ID”在用户表中已经是唯一的,并且您不会得到任何重复的用户。

但如果您只需要唯一的 author_id 数组,您可以使用 @posts.map(&:author_id).uniq

【讨论】:

  • @posts.distinct.pluck(:author_id)一样。
猜你喜欢
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
相关资源
最近更新 更多