Find tags with articles

强颜欢笑 提交于 2020-01-24 23:34:25

问题


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.



来源:https://stackoverflow.com/questions/15618583/find-tags-with-articles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!