10

我正在使用 rails gem 作为可标记,并在两个上下文中标记帖子:标签和主题。

要返回到目前为止用于帖子的所有主题标签的哈希,我可以使用以下代码:

 Post.tag_counts_on(:topics)

但是,我已经创建了一定数量的设置主题标签,如果其中一些主题标签当前没有被用作帖子的标签,那么上面的代码不会返回所述主题。

我想知道是否有办法根据上下文返回所有相关标签——我希望有一个解决方案:

 topics = Tag.topics

为了实现该解决方案,我创建了一个 Tag.rb 模型:

 class Tag < ActiveRecord::Base
   has_many :relationship_topics, :foreign_key => "topic_followed_id", :dependent => :destroy
   has_many :topic_followers, :through => :relationship_topics, :source => :topic_follower
 end

在这里,我有一些代码可以允许以下主题,但仅此而已。

有谁知道我如何根据上下文返回所有标签?

4

4 回答 4

17

我从来没有使用acts-as-taggable-on,但快速浏览代码表明,你可以这样做:

# to get all the tags with context topic with counts
ActsAsTaggableOn::Tagging.
    includes(:tag).
    where(:context => "topics").
    group("tags.name").
    select("tags.name, COUNT(*) as count")

您可能应该查看ActsAsTaggableOn::TaggingActsAsTaggableOn::Tag和 db/migrations 文件夹中的迁移文件,以了解如何进行操作。

如果您不想要计数,只需要标签名称:

tags = ActsAsTaggableOn::Tag.includes(:taggings).
           where("taggings.context = 'topics'").
           select("DISTINCT tags.*")

# usage
tags.each {|tag| puts tag.name}

我希望这能回答你的问题。

于 2011-08-24T03:06:34.903 回答
0

使用Model.tag_counts(来自Usingacts-as-taggable-on 我如何在我的应用程序中找到顶部的标签,比如 10 个标签?):

User.skill_counts # => [<Tag name="joking" count=2>,<Tag name="clowning" count=1>...]
于 2014-04-10T21:54:40.917 回答
0

这对我最有效:

ActsAsTaggableOn::Tag.includes(:taggings).where(taggings:{context:'topics'}).uniq(:name).order(:name)

joins执行或使用标记上下文时的一个限制includes是您只能看到活动的主题。您无法加载主题列表并使用此查询显示它们。查看示例:

没有标记上下文

2.2.1 :009 > ActsAsTaggableOn::Tag.includes(:taggings)
  ActsAsTaggableOn::Tag Load (0.4ms)  SELECT `tags`.* FROM `tags`
  ActsAsTaggableOn::Tagging Load (0.4ms)  SELECT `taggings`.* FROM `taggings` WHERE `taggings`.`tag_id` IN (1, 2, 3)
[
    [0] severe hearing loss {
                    :id => 1,
                  :name => "severe hearing loss",
        :taggings_count => 0
    },
    [1] hearing loss {
                    :id => 2,
                  :name => "hearing loss",
        :taggings_count => 1
    },
    [2] hearing aids {
                    :id => 3,
                  :name => "hearing aids",
        :taggings_count => 0
    }
]

带有标签上下文topics

2.2.1 :016 > ActsAsTaggableOn::Tag.includes(:taggings).where(taggings:{context:'topics'})
  SQL (0.4ms)  SELECT `tags`.`id` AS t0_r0, `tags`.`name` AS t0_r1, `tags`.`taggings_count` AS t0_r2, `taggings`.`id` AS t1_r0, `taggings`.`tag_id` AS t1_r1, `taggings`.`taggable_id` AS t1_r2, `taggings`.`taggable_type` AS t1_r3, `taggings`.`tagger_id` AS t1_r4, `taggings`.`tagger_type` AS t1_r5, `taggings`.`context` AS t1_r6, `taggings`.`created_at` AS t1_r7 FROM `tags` LEFT OUTER JOIN `taggings` ON `taggings`.`tag_id` = `tags`.`id` WHERE `taggings`.`context` = 'topics'
[
    [0] hearing loss {
                    :id => 2,
                  :name => "hearing loss",
        :taggings_count => 1
    }
]
于 2016-04-07T03:05:10.540 回答
-1

方法很简单:

ActsAsTaggableOn::Tag.for_context('topics')
于 2017-01-28T17:37:06.580 回答