Find tags with articles

2019-08-08 03:54发布

问题:

On blog app I want to display list of tags with articles.

class Article < AR::B
  has_and_belongs_to_many :tags
end

class Tag < AR::B
  has_and_belongs_to_many :articles
end

What would Tag scope look like?

Tag.joins(:articles) ... # should return tags associated to at least 1 article

回答1:

One way to do this with Ruby/Rails would be this one.

Tag.includes(:articles).select { |tag| tag.articles.any? }

.includes makes sure that the articles are loaded alongside the tags, which is more efficient than loading them when every tag's articles are iterated upon.

The array is then parsed to only select the ones with articles associated.