Find tags with articles

2019-08-08 04:26发布

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条回答
beautiful°
2楼-- · 2019-08-08 04:35

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.

查看更多
登录 后发表回答