Activerecord 在has_上获取唯一对象,并且_属于_many

Activerecord 在has_上获取唯一对象,并且_属于_many,activerecord,ruby-on-rails-4,Activerecord,Ruby On Rails 4,我有3个实体:提要、剧集、系列。feed有很多集,而且属于很多集。剧集属于系列 我想要的是一个提要的所有系列,以及该提要中该系列的剧集数。您可以通过首先查找所有系列的ID,为给定的一组剧集生成所有系列的完整列表 # uniq insures that any duplicates are removed ids = feed.episodes.map(&:series_id).uniq 然后找到系列本身: series = Series.where(id: ids) 通过简单的计数,

我有3个实体:提要、剧集、系列。feed
有很多集,而且属于很多集。剧集
属于
系列


我想要的是一个提要的所有系列,以及该提要中该系列的剧集数。

您可以通过首先查找所有系列的ID,为给定的一组剧集生成所有系列的完整列表

# uniq insures that any duplicates are removed
ids = feed.episodes.map(&:series_id).uniq
然后找到系列本身:

series = Series.where(id: ids)
通过简单的
计数
,您可以找到每个系列的剧集数:

series.each do |s|
  puts "Series #{s.name} has #{s.episodes.count} episodes"
end
这让我找到了以下解决方案:

ids = @feed.episodes.pluck(:series_id)
@series = Series.find(ids)

@episode_counts = Hash.new(0)
ids.each do |id|
  @episode_counts[id] += 1
end

不幸的是,剧集和连续剧之间的关系是另一种方式。系列节目没有插曲。是的,对不起,
pluck
是正确的选择。我不知道为什么我在第一个答案中写了
pull
,在更新的答案中写了
map(&:series\u id)
:|