删除ActiveRecord habtm查询结果中的重复项

时间:2013-09-10 05:54:13

标签: ruby-on-rails activerecord

我有两个模型has_and_belong_to_many彼此:

class Post < ActiveRecord::Base
  has_and_belongs_to_many :tags, :join_table => :tags_posts
end

class Tag < ActiveRecord::Base
  has_and_belongs_to_many :posts, :join_table => :tags_posts
end

然后我有一个问题:

@tags = Tag.where(name: ["tag1","tag2","tag3"])

我想获得所有包含这些标签的独特帖子,所以我写了这个丑陋的代码:

@posts = [] 
@tags.each do |tag|
  @posts += tag.posts
end
@posts.uniq!

我认为效率低下,因为@posts是一个数组而不是一个&#34; ActiveRecord :: Relation&#34;,我不能直接使用它上面的所有类方法。 有没有更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:2)

@tags = Tag.where(name: %w(tag1 tag2 tag3)).includes(:posts)

应该做的伎俩(%w()创建一个字符串数组,所以没有区别)。它会在一个或两个查询中加载带有标记的所有帖子,无论AR视图中哪个更有效。然后就可以了

@posts = @tags.map(&:posts).flatten.uniq

获取帖子。 map在每个标记上调用posts方法并返回包含这些帖子的数组,但由于您有一个数组数组,因此您需要flatten它。

答案 1 :(得分:1)

您可以使用includes加入这两个表,并在Post模型而不是Tag上进行查询,以便获得独特的帖子。

Post.includes(:tags).where(:tags => { name: %w(tag1 tag2 tag3) })