查找带有文章的标签 [英] Find tags with articles

查看:32
本文介绍了查找带有文章的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在博客应用中,我想显示文章标签列表.

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

标签范围是什么样的?

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

推荐答案

使用 Ruby/Rails 做到这一点的一种方法是这个.

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

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

.includes 确保文章与标签一起加载,这比在迭代每个标签的文章时加载它们更有效.

.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.

这篇关于查找带有文章的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆